使用Apache HttpClient的健壮HTTP
程序员文章站
2022-06-22 12:14:40
...
下面的部分内容来源于《Unlocking Android》一书:
要了解HTTPClient,我们先看一下如何使用核心类来执行HTTP GET和POST方法请求,此处我们结合使用Apache的ResonseHandler和Android的Handler,在与用户界面不同的线程中发起网络请求。
// new a Handler to receive the response by HTTP request. private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { mPrgressDialog.dismiss(); String result = msg.getData().getString("RESPONSE"); mOutput.setText(result); }; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton = (Button) findViewById(R.id.btn); mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mOutput.setText(""); performRequest(url); } }); mOutput = (TextView) findViewById(R.id.output); } // perform HTTP request with HttpRequestHelper asynchronously. private void performRequest(final String url) { final ResponseHandler<String> responseHandler = HttpRequestHelper .getResponseHandlerInstance(mHandler); // show a ProgressDialog to represent that it is woring now, and it // will dismiss after receiving response. mPrgressDialog = ProgressDialog.show(this, "working...", "performing HTTP request"); new Thread() { public void run() { HttpRequestHelper helper = new HttpRequestHelper( responseHandler); // use GET method helper.performGet(url, null, null, null); }; }.start(); }
/** * Helper for HTTP request via GET or POST method. */ public final class HttpRequestHelper { private static final int POST_TYPE = 1; private static final int GET_TYPE = 2; public static final String CONTENT_TYPE = "Content-Type"; public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded"; public static final String MIME_TEXT_PLAIN = "text/plain"; private final ResponseHandler<String> mResponseHandler; public HttpRequestHelper(ResponseHandler<String> responseHandler) { mResponseHandler = responseHandler; } public void performGet(String url, String user, String pwd, final Map<String, String> addtionalHeaders) { performRequest(null, url, user, pwd, addtionalHeaders, null, GET_TYPE); } public void performPost(String contentType, String url, String user, String pwd, Map<String, String> addtionalHeaders, Map<String, String> params) { performRequest(contentType, url, user, pwd, addtionalHeaders, params, POST_TYPE); } public void performPost(String url, String user, String pwd, Map<String, String> addtionalHeaders, Map<String, String> params) { performRequest(MIME_FORM_ENCODED, url, user, pwd, addtionalHeaders, params, POST_TYPE); } private void performRequest(String contentType, String url, String user, String pwd, Map<String, String> headers, Map<String, String> params, int requestType) { DefaultHttpClient client = new DefaultHttpClient(); if (user != null && pwd != null) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pwd)); } final Map<String, String> sendHeaders = new HashMap<String, String>(); if (headers != null && !headers.isEmpty()) { sendHeaders.putAll(headers); } if (POST_TYPE == requestType) { sendHeaders.put(CONTENT_TYPE, contentType); } if (!sendHeaders.isEmpty()) { client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { for (String key : sendHeaders.keySet()) { if (!request.containsHeader(key)) { request.addHeader(key, sendHeaders.get(key)); } } } }); } if (POST_TYPE == requestType) { HttpPost post = new HttpPost(url); List<NameValuePair> nvps = null; if (params != null && !params.isEmpty()) { nvps = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { nvps.add(new BasicNameValuePair(key, params.get(key))); } } if (nvps != null) { try { post.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException e) { // TODO: handle exception } } execute(client, post); } else if (GET_TYPE == requestType) { execute(client, new HttpGet(url)); } } private void execute(HttpClient client, HttpRequestBase method) { try { client.execute(method, mResponseHandler); } catch (Exception e) { BasicHttpResponse erroResponse = new BasicHttpResponse( new ProtocolVersion("HTTP_ERROR", 1, 1), 500, "ERROR"); erroResponse.setReasonPhrase(e.getMessage()); try { mResponseHandler.handleResponse(erroResponse); } catch (Exception e2) { // TODO: handle exception } } } public static ResponseHandler<String> getResponseHandlerInstance( final Handler handler) { return new ResponseHandler<String>() { public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { Message message = handler.obtainMessage(); Bundle data = new Bundle(); HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { try { result = EntityUtils.toString(entity); data.putString("RESPONSE", result); } catch (IOException e) { data.putString("RESPONSE", "Error - " + e.getMessage()); } } else { StatusLine status = response.getStatusLine(); data.putString("RESPONSE", "Error - " + status.getReasonPhrase()); } message.setData(data); message.sendToTarget(); return result; } }; } }
推荐阅读
-
PHP使用http_build_query()构造URL字符串的方法_PHP
-
apache collections 的使用
-
在Linux系统下使用curl自定义HTTP头的方法
-
apache - 奇怪的现象,PHP网站访问首页一直HTTP 408 错误
-
Apache压力测试工具的安装使用
-
python中使用urllib2伪造HTTP报头的2个方法
-
详解.NET Core 使用HttpClient SSL请求出错的解决办法
-
使用ThinkPHP自带的Http类下载远程图片到本地的实现代码_PHP
-
[转载]apache和mysql在windows下的一些使用技巧_MySQL
-
使用php的HTTP请求的库Requests实现美女图片墙,