【发布时间】:2016-02-01 08:28:53
【问题描述】:
我想升级我的代码以发布 json。 第一个实现了 HttpClient 并且工作正常! 我尝试使用 HttpURLconnection 来使用新的实现,但它不起作用!我无法发送任何帖子请求。 我错过了什么?
public class AsyncPostBG extends AsyncTask<String, String, String> {
private ProxyState mData = null;
private String mName = null;
public AsyncPostBG(ProxyState data, String name)
{
mData = data;
mName = name;
}
@Override
protected String doInBackground(String... params){
HttpParams httpParams = new BasicHttpParams();
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost postMethod = new HttpPost(params[0]);
postMethod.setHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setHeader("Accept", "*/*");
postMethod.setHeader("Accept-Encoding", "gzip, deflate");
Gson gson=new Gson();
String json = gson.toJson(mData);
try {
postMethod.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
StatusLine statusLine = response.getStatusLine();
}
catch (UnsupportedEncodingException e){
}
catch (Exception e) {
}
return json;
}
}
这是我的 HttpURLConnection 实现:
private class AsyncStatePostBG extends AsyncTask<String, Void, String> {
private ProxyObj mData = null;
private String mName = null;
public AsyncStatePostBG(ProxyObj data, String name) {
mData = data;
mName = name;
}
@Override
protected String doInBackground(String... params) {
Gson gson = new Gson();
String json = gson.toJson(mData);
HttpURLConnection connection = null;
try {
URL object = new URL(ComURL + "api/state/" + mName);
connection = (HttpURLConnection) object.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json);
streamWriter.flush();
streamWriter.close();
} catch (Exception exception) {
return null;
}
return json;
}
}
【问题讨论】:
-
“它不起作用”到底是什么意思?
-
我收不到任何请求
-
你默默吞下所有异常。但是,它们为诊断问题提供了宝贵的意见。
标签: android httpclient httpurlconnection