【发布时间】:2015-11-14 17:09:52
【问题描述】:
我使用HttpClient 和目标 API 19 开发了一个 Android 应用程序。为了进行一些更新,我更新了目标 API 22。当我这样做时,我注意到大量以前的实现现在已被弃用。因此,我尝试使用更新更好的HttpUrlConnection,但我在这方面遇到了一些困难。
我已经经历过关于 SO 的各种线程,但我对此类连接知之甚少。
这是我用于 API 19 的代码 -
HttpClient client = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost post = new HttpPost("https://example.com/exchweb/bin/auth/owaauth.dll");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("destination", "https://example.com/exchange/" + username.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("flags",
"0"));
nameValuePairs.add(new BasicNameValuePair("rdoPublic", "0"));
nameValuePairs.add(new BasicNameValuePair("rdoTrusted", "4"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post,httpContext);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
// Saving line for use
startActivity(new Intent(SplashActivity.this,MainActivity.class));
finish();
}
}
catch (IOException e) {
e.printStackTrace();
}
它可能在某个地方得到了回答,但是有很多例子可以看,而且我作为一个新手很难找到一个有效的例子。
还有一个问题 - HttpUrlConnection 是否像 HttpContext 一样保存会话本身?如果没有,请帮助我也知道这一点,非常感谢。
感谢收听!如果您需要更多内容,请发表评论。
干杯
【问题讨论】:
-
查看以下链接,希望您能找到答案:developer.android.com/reference/java/net/HttpURLConnection.html
-
我建议你跳过发明轮子的时间,开始使用
Retrofit。 -
@Fox 你能简单解释一下你的观点吗?
-
square.github.io/retrofit - 在不创建连接、上下文、阅读器和其他东西的情况下帮助发出 http 请求的库。
-
在这里您可以找到a list of libraries,您可以使用它让生活更轻松。 HttpURLConnection 是 Google 推荐的,但我确信他们不会“本机”使用它,他们可能使用 Volley。
标签: java android http-post httpurlconnection androidhttpclient