我有一个用Java编写的Android应用程序代码。通过使用HttpPost和DefaultHttpClient库。目前,我正在对其进行重新编码,以使用HttpURLConnection替换HttpPost和DefaultHttpClient库,因为已经描述了DefaultHttpClient。
我已经为我的项目完成了一次,并且成功了。
但是在当前项目中,使用HttpURLConnection而不是DefaultHttpClient时,无法从Web服务获得相同的响应。有人能帮我请我在哪里做错吗?
这是旧的代码:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
try {
httpPost.setEntity(new StringEntity(postParameter));
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
这是我的新代码
_Url = new URL(Url);
HttpURLConnection urlconnection = (HttpURLConnection) _Url.openConnection();
urlconnection.setRequestMethod(Type);
urlconnection.setConnectTimeout(Timeout);
urlconnection.setUseCaches(false);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os));
writer.write(postParameter);
writer.flush();
writer.close();
os.close();
urlconnection.connect();
该代码正在运行,没有任何错误,但是Web服务没有给出与旧代码相同的响应。
最佳答案
您没有得到输入流,请尝试以下代码
try {
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
URL url = new URL(UrlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept",
"application/json");
urlConnection.setRequestProperty("Content-Type",
"application/json");// setting your headers its a json in my case set your appropriate header
urlConnection.setDoOutput(true);
urlConnection.connect();// setting your connection
OutputStream os = null;
os = new BufferedOutputStream(
urlConnection.getOutputStream());
os.write(postParameter.toString().getBytes());
os.flush();// writing your data which you post
StringBuffer buffer = new StringBuffer();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
// reading your response
is.close();
urlConnection.disconnect();// close your connection
return buffer.toString();
} catch (Exception e) {
}