And*_*yld 6 java android http-post
我正在HttpPostAndroid中创建一个对象,以便与客户端运行的服务器进行通信.不幸的是,服务器没有向我们提供非常有用的错误消息; 我希望将HttpPost对象的内容看作一个字符串,这样我就可以将它发送给我们的客户端,他可以将它与他期望的内容进行比较.
如何将HttpPost对象转换为一个字符串,反映它到达服务器时的外观?
我通常以这种方式发布(服务器答案是一个 JSON 对象):
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
postData 是:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
@SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
3944 次 |
| 最近记录: |