在这里,我们将给大家分享关于HttpURLConnection将JSONPOST请求发送到Apache/PHP的知识,让您更了解http发送json数据的本质,同时也会涉及到如何更有效地Android
在这里,我们将给大家分享关于HttpURLConnection将JSON POST请求发送到Apache / PHP的知识,让您更了解http发送json数据的本质,同时也会涉及到如何更有效地Android-HttpURLConnection-Get与Post请求登录功能、Android无法使用HttpURLConnection发送GET请求、Apache http客户端或URLConnection、Http - Do a POST with HttpURLConnection的内容。
本文目录一览:- HttpURLConnection将JSON POST请求发送到Apache / PHP(http发送json数据)
- Android-HttpURLConnection-Get与Post请求登录功能
- Android无法使用HttpURLConnection发送GET请求
- Apache http客户端或URLConnection
- Http - Do a POST with HttpURLConnection
HttpURLConnection将JSON POST请求发送到Apache / PHP(http发送json数据)
我在HttpURLConnection和OutputStreamWriter方面挣扎。
代码实际上到达了服务器,因为我确实收到了有效的错误响应。发出了POST请求,但服务器端未收到任何数据。
正确使用此东西的任何提示均受到高度赞赏。
该代码在AsyncTask中
protected JSONObject doInBackground(Void... params) { try { url = new URL(destination); client = (HttpURLConnection) url.openConnection(); client.setDoOutput(true); client.setDoInput(true); client.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); client.setRequestMethod("POST"); //client.setFixedLengthStreamingMode(request.toString().getBytes("UTF-8").length); client.connect(); Log.d("doInBackground(Request)", request.toString()); OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream()); String output = request.toString(); writer.write(output); writer.flush(); writer.close(); InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d("doInBackground(Resp)", result.toString()); response = new JSONObject(result.toString()); } catch (JSONException e){ this.e = e; } catch (IOException e) { this.e = e; } finally { client.disconnect(); } return response; }
我正在尝试发送的JSON:
JSONObject request = { "action":"login", "user":"mogens", "auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7", "location":{ "accuracy":25, "provider":"network", "longitude":120.254944, "latitude":14.847808 } };
我从服务器得到的响应:
JSONObject response = { "success":false, "response":"Unknown or Missing action.", "request":null };
我应该得到的回应是:
JSONObject response = { "success":true, "response":"Welcome Mogens Burapa", "request":"login" };
服务器端PHP脚本:
<?php $json = file_get_contents(''php://input''); $request = json_decode($json, true); error_log("JSON: $json"); error_log(''DEBUG request.php: '' . implode('', '',$request)); error_log("============ JSON Array ==============="); foreach ($request as $key => $val) { error_log("$key => $val"); } switch($request[''action'']) { case "register": break; case "login": $response = array( ''success'' => true, ''message'' => ''Welcome '' . $request[''user''], ''request'' => $request[''action''] ); break; case "location": break; case "nearby": break; default: $response = array( ''success'' => false, ''response'' => ''Unknown or Missing action.'', ''request'' => $request[''action''] ); break; } echo json_encode($response); exit;?>
以及Android Studio中的logcat输出:
D/doInBackground(Request)﹕ {"action":"login","location":{"accuracy":25,"provider":"network","longitude":120.254944,"latitude":14.847808},"user":"mogens","auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7"}D/doInBackground(Resp)﹕ {"success":false,"response":"Unknown or Missing action.","request":null}
如果附加?action=login
到,则URL
可以从服务器获得成功响应。但是只有 动作 参数在服务器端注册。
{"success":true,"message":"Welcome ","request":"login"}
结论必须是没有数据通过 URLConnection.write(output.getBytes("UTF-8"));
好吧,数据毕竟会被传输。
@greenaps提供的解决方案可以解决问题:
$json = file_get_contents(''php://input'');$request = json_decode($json, true);
上面的PHP脚本已更新以显示解决方案。
答案1
小编典典echo (file_get_contents(''php://input''));
将向您显示json文本。像这样工作:
$jsonString = file_get_contents(''php://input'');$jsonObj = json_decode($jsonString, true);
Android-HttpURLConnection-Get与Post请求登录功能
HttpURLConnection 在这请求方式是Java包中的;
AndroidManifest.xml配置权限:
<!-- 访问网络是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 设置壁纸是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.SET_WALLPAPER" />
MainActivity7.java :
package liudeli.async;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MainActivity7 extends Activity implements View.OnClickListener {
private EditText etName;
private EditText etPwd;
private Button btLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
etName = findViewById(R.id.et_name);
etPwd = findViewById(R.id.et_pwd);
btLogin = findViewById(R.id.bt_login);
btLogin.setOnClickListener(this);
}
// 请求服务器的地址
private final String PATH = "http://127.0.0.1:8080/LoginServlet";
@Override
public void onClick(View v) {
// 拼装参数
final Map<String, String> map = new HashMap<>();
map.put("name", etName.getText().toString());
map.put("pwd", etPwd.getText().toString());
// 联网操作必须开启线程,执行异步任务
new Thread(){
@Override
public void run() {
super.run();
try {
// Get请求方式,参数操作是拼接在链接
loginByGet(PATH, map);
// Post请求方式,参数操作是封装实体对象
loginByPost(PATH, map);
} catch (Exception e) {
e.printStackTrace();
threadRunToToast("登录是程序发生异常");
}
}
}.start();
}
/**
* HttpURLConnection Get 方式请求
* @param path 请求的路径
* @param map 请求的参数
* 拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
*/
private void loginByGet(String path, Map<String, String> map) throws Exception{
// 拼接路径地址 拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
StringBuffer pathString = new StringBuffer(path);
pathString.append("?");
// 迭代遍历Map
for (Map.Entry<String, String> mapItem : map.entrySet()) {
String key = mapItem.getKey();
String value = mapItem.getValue();
// name=zhangsan&
pathString.append(key).append("=").append(value).append("&");
}
// name=zhangsan&pwd=123456& 删除最后一个符号& 删除后:name=zhangsan&pwd=123456
pathString.deleteCharAt(pathString.length() - 1);
// 最后完整路径地址是:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
// 第一步 包装网络地址
URL url = new URL(pathString.toString());
// 第二步 打开连接对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 第三步 设置连接超时时长
httpURLConnection.setConnectTimeout(5000);
// 第四步 设置请求方式Get
httpURLConnection.setRequestMethod("GET");
// 第五步 发生请求 ⚠注意:只有在>>httpURLConnection.getResponseCode(); 才向服务器发请求
int responseCode = httpURLConnection.getResponseCode();
// 第六步 判断请求码是否成功
// 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
if(responseCode == HttpURLConnection.HTTP_OK) {
// 第七步 获取服务器响应的流
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (-1 != (len = inputStream.read())) {
// 把存取到bytes的数据,写入到>>ByteArrayOutputStream
bos.write(bytes, 0, len);
}
// 第六步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的 success代表登录成功
String loginResult = bos.toString();
if ("success".equals(loginResult)) {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
threadRunToToast("登录成功");
} else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
threadRunToToast("登录失败");
}
// 第七步 关闭流
inputStream.close();
bos.close();
} else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败,请检查网络!", Toast.LENGTH_SHORT).show();
threadRunToToast("登录失败,请检查网络!");
}
}
/**
* HttpURLConnection Get 方式请求
* @param path 请求的路径
* @param params 请求的参数
* 路径:http://127.0.0.1:8080/LoginServlet
*
* 参数:
* name=zhangsan
* pwd=123456
*/
private void loginByPost(String path, Map<String, String> params) throws Exception {
// ------------------------------------------------ 以下是实体拼接帮助
/**
* 拼实体 注意⚠️:是需要服务器怎么配置 这里就要怎么拼接 例如:user.name=zhangsan&user.pwd=123
* 注意:⚠ 这不是访问服务器的地址,这是拼接实体
*/
StringBuilder paramsString = new StringBuilder();
for(Map.Entry<String, String> entry: params.entrySet()){
paramsString.append(entry.getKey());
paramsString.append("=");
paramsString.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
paramsString.append("&");
}
/**
* user.name=zhangsan&user.pwd=123& 删除最后一个符号& 删除后:user.name=zhangsan&user.pwd=123
* 注意:⚠ 这不是访问服务器的地址,这是拼接实体
*/
paramsString.deleteCharAt(paramsString.length() - 1);
// 理解为实体
byte[] entity = paramsString.toString().getBytes();
// ------------------------------------------------ 以下是 HttpURLConnection Post 访问 代码
// 第一步 包装网络地址
URL url = new URL(path);
// 第二步 打开连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 第三步 设置连接超时时长
conn.setConnectTimeout(5000);
// 第四步 设置请求方式 POST
conn.setRequestMethod("POST");
/**
* 第五步 设置请求参数
* 请求参数类型
*/
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 请求实体的长度(字节)
conn.setRequestProperty("Content-Length", entity.length+"");
// 第六步 允许对外输出
conn.setDoOutput(true);
// 第七步 得到输出流 并把实体输出写出去
OutputStream os = conn.getOutputStream();
os.write(entity);
// 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
// 第八步 获取服务器响应的流
InputStream inputStream = conn.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (-1 != (len = inputStream.read())) {
// 把存取到bytes的数据,写入到>>ByteArrayOutputStream
bos.write(bytes, 0, len);
}
// 第九步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的 success代表登录成功
String loginResult = bos.toString();
if ("success".equals(loginResult)) {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
threadRunToToast("登录成功");
} else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
threadRunToToast("登录失败");
}
// 第十步 关闭流
inputStream.close();
bos.close();
}
}
/**
* 在 主线程 子线程 中提示,属于UI操作
*/
private void threadRunToToast(final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main7.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名"
/>
<EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码"
/>
<EditText
android:id="@+id/et_pwd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
<Button
android:id="@+id/bt_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="login"
/>
</LinearLayout>
Android无法使用HttpURLConnection发送GET请求
我不确定是什么原因,但是当我使用’POST’发送请求时,我的 JSON服务器(我使用JAX-RS)会返回一个空白页面.
这是我的代码片段:
// Create the connection HttpURLConnection con = (HttpURLConnection) new URL(getUrl() + uriP).openConnection(); // Add cookies if necessary if (cookies != null) { for (String cookie : cookies) { con.addRequestProperty("Cookie",cookie); Log.d("JSONServer","Added cookie: " + cookie); } } con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestMethod("GET"); con.setConnectTimeout(20000); // Add ''Accept'' property in header otherwise JAX-RS/CXF will answer a XML stream con.addRequestProperty("Accept","application/json"); // Get the output stream OutputStream os = con.getoutputStream(); // !!!!! HERE THE REQUEST METHOD HAS BEEN CHANGED !!!!!! OutputStreamWriter wr = new OutputStreamWriter(os); wr.write(requestP); // Send the request wr.flush();
谢谢你的回答.
埃里克
解决方法
如果您需要在GET中将数据发送到服务器,则需要以正常方式在URL参数中进行编码.
Apache http客户端或URLConnection
我需要在android应用程序上下载网页,并且很难决定是使用android apache http客户端还是使用Java的URLConnection。
有什么想法吗?
Http - Do a POST with HttpURLConnection
In a GET request, the parameters are sent as part of the URL.
In a POST request, the parameters are sent as a body of the request, after the headers.
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
This code should get you started:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.net/new-message.php");
Map<String, Object> params = new LinkedHashMap<>();
params.put("name", "Freddie the Fish");
params.put("email", "fishie@seamail.example.com");
params.put("reply_to_thread", 10394);
params.put("message",
"Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He''s so shellfish.");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0)
postData.append(''&'');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append(''='');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char) c);
}
}
If you want the result as a String
instead of directly printed out do:
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString();
参考:
http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily
http://hgoebl.github.io/DavidWebb/
今天的关于HttpURLConnection将JSON POST请求发送到Apache / PHP和http发送json数据的分享已经结束,谢谢您的关注,如果想了解更多关于Android-HttpURLConnection-Get与Post请求登录功能、Android无法使用HttpURLConnection发送GET请求、Apache http客户端或URLConnection、Http - Do a POST with HttpURLConnection的相关知识,请在本站进行查询。
本文标签: