gpt4 book ai didi

java - 使用 HttpURLConnection 代替 HttpPost

转载 作者:行者123 更新时间:2023-12-02 04:42:07 25 4
gpt4 key购买 nike

我有一个用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();

代码运行时没有任何错误,但网络服务没有给出与旧代码相同的响应。

最佳答案

您没有获取输入流,请尝试以下代码

         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) {
}

关于java - 使用 HttpURLConnection 代替 HttpPost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30069084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com