设为首页 收藏本站
查看: 651|回复: 0

[经验分享] 使用Apache HttpClient的健壮HTTP

[复制链接]

尚未签到

发表于 2017-1-7 09:52:25 | 显示全部楼层 |阅读模式
  下面的部分内容来源于《Unlocking Android》一书:
  要了解HTTPClient,我们先看一下如何使用核心类来执行HTTP GET和POST方法请求,此处我们结合使用Apache的ResonseHandler和Android的Handler,在与用户界面不同的线程中发起网络请求。
  
DSC0000.png

 
// 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;
}
};
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-324969-1-1.html 上篇帖子: Ext + org.apache.commons.fileupload上传文件 下篇帖子: Apache Struts 2 Documentation--JSON Plugin
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表