java 如何从 HttpClient 切换到 HttpUrlConnection?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26898667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to switch from HttpClient to HttpUrlConnection?
提问by Bhargav Thanki
I am creating an Android application and I send data from Android application to servlet through HttpClient. I use HttpPost method.
我正在创建一个 Android 应用程序,并通过 HttpClient 将数据从 Android 应用程序发送到 servlet。我使用 HttpPost 方法。
I read in Android developer site that Apache HttpClient library has some bug in Android Froyo 2.2 and after all it's good practice to use HttpUrlConnection instead HttpPost. So I want to convert my HttpPost code to HttpUrlConnectio but don't know how.
我在 Android 开发者网站上读到 Apache HttpClient 库在 Android Froyo 2.2 中有一些错误,毕竟使用 HttpUrlConnection 而不是 HttpPost 是一个好习惯。所以我想将我的 HttpPost 代码转换为 HttpUrlConnectio 但不知道如何。
I am posting my Android code as well as servlet code here
我在这里发布我的 Android 代码以及 servlet 代码
Android code
安卓代码
private String postData(String valueIWantToSend[])
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("param2", valueIWantToSend[1]));
nameValuePairs.add(new BasicNameValuePair("param3", valueIWantToSend[2]));
nameValuePairs.add(new BasicNameValuePair("param4", valueIWantToSend[3]));
nameValuePairs.add(new BasicNameValuePair("param5", valueIWantToSend[4]));
nameValuePairs.add(new BasicNameValuePair("param6", valueIWantToSend[5]));
nameValuePairs.add(new BasicNameValuePair("param7", valueIWantToSend[6]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
//origresponseText=readContent(response);
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
return null;
}
and here is my servlet code
这是我的 servlet 代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
Enumeration paramNames = request.getParameterNames();
String params[] = new String[7];
int i=0;
while(paramNames.hasMoreElements())
{
String paramName = (String) paramNames.nextElement();
System.out.println(paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
System.out.println(params[i]);
i++;
}
}
采纳答案by Jeff Mixon
You should absolutely be using HttpUrlConnection
:
你绝对应该使用HttpUrlConnection
:
For Gingerbread and better, HttpURLConnection is the best choice... New applications should use HttpURLConnection...
对于 Gingerbread 和更好的,HttpURLConnection 是最好的选择...新的应用程序应该使用 HttpURLConnection...
However, there is no easy way just to "switch". The APIs are totally different. You are going to have to rewrite your networking code. There are perfect examples in the documentationon how to submit a GET and POST requests as well as in the SDK sample apps.
然而,没有简单的方法来“切换”。API 完全不同。您将不得不重写您的网络代码。文档中有关于如何提交 GET 和 POST 请求以及 SDK 示例应用程序的完美示例。
回答by hgoebl
When I read the already mentioned Google postabout best practices doing HTTP requests in newer versions of Android, I thought somebody was kidding me. HttpURLConnection
is really a nightmare to use, compared to almost any other way to communicate with HTTP servers (apart from direct Socket communication).
当我阅读已经提到的关于在较新版本的 Android 中执行 HTTP 请求的最佳实践的Google 帖子时,我以为有人在开玩笑。HttpURLConnection
与几乎任何其他与 HTTP 服务器通信的方式(除了直接 Socket 通信)相比,使用起来真的是一场噩梦。
I didn't find a really slim library for Android to do the heavy lifting, so I wrote my own. You can find it at DavidWebbincluding a list of alternative librarieswhich I found (unfortunately) after developing the library.
我没有找到一个非常小巧的 Android 库来完成繁重的工作,所以我自己写了一个。您可以在DavidWebb 上找到它,其中包括我在开发库后(不幸地)找到的替代库列表。
Your code would look more or less like this:
你的代码看起来或多或少是这样的:
public void testPostToUrl() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
Response<String> response = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.asString();
assertEquals(200, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().contains("my expected result"));
}
public void testPostToUrlShorter() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
String result = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.ensureSuccess()
.asString()
.getBody();
assertTrue(result.contains("my expected result"));
}