gpt4 book ai didi

android - 从 AndroidHttpClient 转换为 HttpUrlConnection

转载 作者:行者123 更新时间:2023-11-30 02:41:24 25 4
gpt4 key购买 nike

我写了下面的代码,它工作正常:

private static final String URL = "http://test.net/api/mobile/logininfo";
private AndroidHttpClient client = AndroidHttpClient.newInstance("");

HttpPost request = new HttpPost(URL);
request.addHeader("Content-Type", "application/json; charset=utf-8");
request.addHeader("Cookie", sessionId);

String username = "test";
String osVersion = android.os.Build.VERSION.RELEASE;

String params = "{\"username\":\"" + username
+ "\",\"osVersion\":\"" + osVersion
+ "\"}";

request.setEntity(new StringEntity(params));
HttpResponse response = client.execute(request);

String res = new BasicResponseHandler()
.handleResponse(response);
JSONObject obj = (JSONObject) new JSONTokener(res).nextValue();

//do something with JSONObject

但是,当我阅读网络处理的开发人员最佳实践 (http://android-developers.blogspot.com/2011/09/androids-http-clients.html) 时,我发现 HttpURLConnection 是比 AndroidHttpClient 更好的选择。

如何将我的代码转换为使用 HttpURLConnection 而不是 AndroidHttpClient?

谢谢

最佳答案

我找到了解决方案。以下是 HttpURLConnection 的等效代码:

URL url = new URL("http://test.net/api/mobile/logininfo");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", sessionId);
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
conn.setRequestProperty("Expect", "100-continue");

String osVersion = android.os.Build.VERSION.RELEASE;

String params = "{\"username\":\"" + username
+ "\",\"osVersion\":\"" + osVersion
+ "\"}";

PrintWriter out = new PrintWriter(conn.getOutputStream());
out.println(params);
out.flush();

conn.connect();
int responseCode = conn.getResponseCode();

if (responseCode != 200)
return null;

StringBuilder response = new StringBuilder();
Scanner scanner = new Scanner(conn.getInputStream());
while (scanner.hasNext()) {
response.append(scanner.nextLine());
}
scanner.close();

JSONObject obj = (JSONObject) new JSONTokener(
response.toString()).nextValue();

//do something with JSONObject

谢谢

关于android - 从 AndroidHttpClient 转换为 HttpUrlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25707110/

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