请帮助我,我在使用HttpUrlConnection类将JSON-object作为参数主体发送POST请求时遇到问题。我一直在寻找同样的问题,我已经尝试了解决方案,但没有一个适合我的情况。这是我的代码(我在AsyncTask类中调用此方法):`
public JSONObject postData(String url, JSONObject params) throws IOException{
JSONObject ret=null;
OutputStream os=null;
InputStream is=null;
HttpURLConnection cnHost=null;
URL host=null;
String jsStr=null;
StringBuilder result=null;
String json="";
try {
//TODO Open host connection
host = new URL(url);
jsStr = "key="+params;
cnHost = (HttpURLConnection) host.openConnection();
//TODO set request Attribute
//Set Connection attributes
cnHost.setDoInput(true);
cnHost.setDoOutput(true);
cnHost.setUseCaches (false);
cnHost.setAllowUserInteraction(false);
cnHost.setReadTimeout(10000);
cnHost.setConnectTimeout(15000);
cnHost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;");
cnHost.setRequestMethod("POST");
//TODO Start streaming request
cnHost.connect();
os =cnHost.getOutputStream();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os));
wr.write(jsStr);
wr.flush();
wr.close();
//TODO get Response
try {
BufferedInputStream in = new BufferedInputStream(cnHost.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line); }
//TODO cast to json Object
json = result.toString();
in.close();
reader.close();
ret = new JSONObject(json);
} catch (Exception e){
Log.d("Get_response","inner_Exception");
e.printStackTrace();
}
}catch (IOException e) {
//TODO Add IOException Handler
Log.d("IOException", "Descp:");
e.printStackTrace();
}catch (NullPointerException e){
//TODO Add NUllPointerException
Log.d("NullPointerException","Descp:");
e.printStackTrace();
} catch (Exception e){
//TODO Add Exception Handler
Log.d("Exception","Descp");
e.printStackTrace();
} finally {
//region Log postData (removed when no bug)
Log.d("bodyContent:", jsStr);
Log.d("RequestMethod", cnHost.getRequestMethod());
Log.d("DoInput", String.valueOf(cnHost.getDoInput()));
Log.d("DoOutput", String.valueOf(cnHost.getDoOutput()));
Log.d("FixLengthStreamMode", String.valueOf(jsStr.getBytes().length));
Log.d("Content-Type", cnHost.getRequestProperty("Content-Type"));
Log.d("Response_Message",json);
//endregion
cnHost.disconnect();
}
return ret;
} `
以下是调用上述方法的代码:
try{
JSONObject jsParam=new JSONObject();
jsParam.put("method", URLEncoder.encode("check","UTF-8"));
JSONObject jsResponse=postData(myUrl,jsParam);
} catch (Exception e){
e.printStackTrace;
} finally{
if(jsObj==null){
Log.d("NullJson","Yes, jsObj return null");
} else {
Log.d("ValidResponse",jsObj.toString());
}
}
当此请求从android-app发布时,Web服务总是响应,表示request-body包含的是空消息。但是当我使用Postman-client发送它时,Web服务响应有效消息。在我的Postman代码下面:
POST /mro/public/index.php? HTTP/1.1
Host: mro.alfamartku.com
Content-Type: application/x-www-form-urlencoded;
Cache-Control: no-cache
Postman-Token: 25463d97-b821-7016-d3e7-5e256d69a31a
key={"method":"check"}
答案 0 :(得分:1)
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
您错过的部分在以下内容中......即,如下..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.write(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
剩下的事情你可以做到。