目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)

修改了一下,可以自定义请求的Header,增加了对POST表单数据的支持。

1. 建立一个连接配置类
class UserAgentConfig {public String host;public String scheme = "http";public int port = 80;public int timeoutConnection = 3000;public int timeoutSocket = 20000;public String username = "";public String password = "";}

2. 封装请求类
public class HttpRequest {private String mUrl;private UserAgentConfig mConfig = null;private HashMap<String, String> mHeaders = null;private HttpEntity mBody = null;private int mStatus = -1;public HttpRequest(String url) {mUrl = url;}public void addHeader(String key, String value) {if (mHeaders == null)mHeaders = new HashMap<String, String>();mHeaders.put(key, value);}public void clearHeader() {mHeaders.clear();mHeaders = null;}public void setConfig(UserAgentConfig config) {mConfig = config;}public void setPostBody(List<BasicNameValuePair> body) {try {mBody = new UrlEncodedFormEntity(body, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}public void setPostBody(String body) {try {mBody = new StringEntity(body);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}public void execute() throws ClientProtocolException, IOException {httprequest();}public int getStatusCode() {return mStatus;}/** * get "Stream" as response *  * @return response in stream * @throws IOException * @throws ClientProtocolException */public InputStream getStream() throws ClientProtocolException, IOException {HttpEntity entity = httprequest();InputStream ret = null;if (entity != null) {try {byte[] b = EntityUtils.toByteArray(entity);ret = new ByteArrayInputStream(b);} finally {release(entity);}}return ret;}/** * get "String" as response *  * @return response in string * @throws IOException * @throws ClientProtocolException */public String getString() throws ClientProtocolException, IOException {HttpEntity entity = httprequest();String ret = null;if (entity != null) {try {ret = EntityUtils.toString(entity);} finally {release(entity);}}return ret;}/** * release connection resource *  * @param entity */private static void release(HttpEntity entity) {try {entity.consumeContent();} catch (IOException e) {e.printStackTrace();}}/** * get "HttpEntity" as response *  * @return * @throws IOException * @throws ClientProtocolException */private HttpEntity httprequest() throws ClientProtocolException,IOException {System.out.println(mUrl);DefaultHttpClient client = null;HttpEntity entity = null;BasicHttpParams httpParameters = new BasicHttpParams();if (mConfig != null) {// set connection timeoutHttpConnectionParams.setConnectionTimeout(httpParameters,mConfig.timeoutConnection);}client = new DefaultHttpClient(httpParameters);DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, true);client.setHttpRequestRetryHandler(retryHandler);// set username & password if availableif (mConfig != null&& !(isEmpty(mConfig.username) && isEmpty(mConfig.password))) {AuthScope as = new AuthScope(mConfig.host, mConfig.port);UsernamePasswordCredentials upc = new UsernamePasswordCredentials(mConfig.username, mConfig.password);client.getCredentialsProvider().setCredentials(as, upc);}// check get or post method by paramsHttpRequestBase method = null;if (mBody == null) {method = new HttpGet(mUrl);} else {method = new HttpPost(mUrl);((HttpPost) method).setEntity(mBody);}// set request headerif (mHeaders != null) {Iterator<?> iter = mHeaders.entrySet().iterator();while (iter.hasNext()) {Map.Entry<?, ?> entry = (Entry<?, ?>) iter.next();String key = (String) entry.getKey();String val = (String) entry.getValue();method.setHeader(key, val);}}// get responseHttpResponse response = null;if (mConfig == null || isEmpty(mConfig.host) || isEmpty(mConfig.scheme)) {// only URL is availableresponse = client.execute(method);} else {BasicHttpContext localContext = new BasicHttpContext();BasicScheme basicAuth = new BasicScheme();localContext.setAttribute("preemptive-auth", basicAuth);HttpHost targetHost = new HttpHost(mConfig.host, mConfig.port,mConfig.scheme);response = client.execute(targetHost, method, localContext);}mStatus = response.getStatusLine().getStatusCode();entity = response.getEntity();return entity;}/** * Check the string is valuable or not *  * @param s * @return true if s is null or s.length() == 0 false otherwise */private boolean isEmpty(String s) {return s == null || s.length() == 0;}}

3. 调用
GET请求
HttpRequest request = new HttpRequest("...");request.execute();

UserAgentConfig config = new UserAgentConfig();config.host = "...";config.username = "...";config.password = "...";HttpRequest request = new HttpRequest("...");request.setConfig(config);System.out.println(request.getString());

POST请求
HttpRequest request = new HttpRequest("...");request.addHeader("...", "...");request.setPostBody("....");request.execute();System.out.println(request.getStatusCode());

更多相关文章

  1. Android(安卓)几种网络请求。
  2. Android(安卓)Retrofit网络请求Service,@Path、@Query、@QueryMap
  3. Android之Retrofit2.0 处理返回json报文并转换成bean对象
  4. Okhttp的简单介绍和使用(一)
  5. Android网络连接1——DefaultHttpClient
  6. 使用HttpURLConnection访问网络
  7. Android(安卓)疯狂造轮子 常用工具类 直接拿来用!
  8. Android(安卓)Okhttp主流程源码分析
  9. 关于android监听H5发送的事件实现方法。

随机推荐

  1. Android——Bitmap和Canvas
  2. Android(安卓)Opengl es 写字 笔记
  3. android 监控应用进程
  4. android 控制EditText字符长度[配置控制 
  5. Android资源优化
  6. Android(安卓)Bitmap和Canvas学习笔记
  7. [万能方法] Android(安卓)Studio 调试出
  8. android中控制AlertDialog的关闭
  9. android 起动APP时锁住(Lock apps)
  10. Kotlin继承