HttpURLConnection和HttpClient的简单用法
生活随笔
收集整理的這篇文章主要介紹了
HttpURLConnection和HttpClient的简单用法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
HttpURLConnection的簡(jiǎn)單用法:先通過一個(gè)URL創(chuàng)建一個(gè)conn對(duì)象,然后就是可以設(shè)置get或者是post方法,接著用流來讀取響應(yīng)結(jié)果即可
String html = null;long startTime = System.currentTimeMillis();try {URL url = new URL("http://www.baidu.com/");HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5 * 1000);if (conn.getResponseCode() == 200) {BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = reader.readLine()) != null) {html += line;}/*//第二種方法
InputStream is = conn.getInputStream();byte []buffer = new byte[is.available()];is.read();String result = new String(buffer);*/}} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
?
HttpClient的簡(jiǎn)單用法:
/*** @param url* @return 1.頁面源碼;2.TimeOut;3.沒正確響應(yīng),返回null*/public String doHttpGet(String url) {String result = null;//通過url來創(chuàng)建httpGet對(duì)象HttpGet httpGet = new HttpGet(url);httpClient = new DefaultHttpClient();// 請(qǐng)求超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);// 讀取超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);try {httpResponse = httpClient.execute(httpGet);// 判斷響應(yīng)的狀態(tài)碼,200表示成功響應(yīng)了請(qǐng)求if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 得到結(jié)果集result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");// result = new String(result.getBytes(),"utf-8");//System.out.println(result);} else {System.err.println("未得到正確的響應(yīng),響應(yīng)嗎:"+ httpResponse.getStatusLine().getStatusCode());}} catch (ClientProtocolException e) {} catch (IOException e) {return "TimeOut";}return result;}/*** @param url* @param paramsList* @return 1.頁面源碼;2.TimeOut;3.沒有響應(yīng),返回null*/public String doHttpPost(String url, List<NameValuePair> paramsList) {String result = null;// 根據(jù)url創(chuàng)建HttpPost實(shí)例HttpPost httpPost = new HttpPost(url);httpClient = new DefaultHttpClient();// 請(qǐng)求超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);// 讀取超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);try {// 設(shè)置HttpPost請(qǐng)求參數(shù)必須用NameValuePair對(duì)象httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));// 發(fā)送post請(qǐng)求httpResponse = httpClient.execute(httpPost);// 判斷響應(yīng)的狀態(tài)碼,200表示成功響應(yīng)了請(qǐng)求if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result = EntityUtils.toString(httpResponse.getEntity());//System.out.println(result);} else {System.err.println("未得到正確的響應(yīng),響應(yīng)嗎:"+ httpResponse.getStatusLine().getStatusCode());}} catch (UnsupportedEncodingException e) {System.out.println("UnsupportedEncodingException");} catch (ParseException e) {System.out.println("ParseException");} catch (IOException e) {return "TimeOut";}return result;}?
工具類NetManager:
package com.kale.mycmcc.net;import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils;public class NetManager {public static int TIME_OUT = 4 * 1000;private HttpResponse httpResponse = null;private HttpClient httpClient;/*** @param url* @return 1.頁面源碼;2.TimeOut;3.沒正確響應(yīng),返回null*/public String doHttpGet(String url) {String result = null;//通過url來創(chuàng)建httpGet對(duì)象HttpGet httpGet = new HttpGet(url);httpClient = new DefaultHttpClient();// 請(qǐng)求超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);// 讀取超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);try {httpResponse = httpClient.execute(httpGet);// 判斷響應(yīng)的狀態(tài)碼,200表示成功響應(yīng)了請(qǐng)求if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 得到結(jié)果集result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");// result = new String(result.getBytes(),"utf-8");//System.out.println(result);} else {System.err.println("未得到正確的響應(yīng),響應(yīng)嗎:"+ httpResponse.getStatusLine().getStatusCode());}} catch (ClientProtocolException e) {} catch (IOException e) {return "TimeOut";}return result;}/*** @param url* @param paramsList* @return 1.頁面源碼;2.TimeOut;3.沒有響應(yīng),返回null*/public String doHttpPost(String url, List<NameValuePair> paramsList) {String result = null;// 根據(jù)url創(chuàng)建HttpPost實(shí)例HttpPost httpPost = new HttpPost(url);httpClient = new DefaultHttpClient();// 請(qǐng)求超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);// 讀取超時(shí) httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);try {// 設(shè)置HttpPost請(qǐng)求參數(shù)必須用NameValuePair對(duì)象httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));// 發(fā)送post請(qǐng)求httpResponse = httpClient.execute(httpPost);// 判斷響應(yīng)的狀態(tài)碼,200表示成功響應(yīng)了請(qǐng)求if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result = EntityUtils.toString(httpResponse.getEntity());//System.out.println(result);} else {System.err.println("未得到正確的響應(yīng),響應(yīng)嗎:"+ httpResponse.getStatusLine().getStatusCode());}} catch (UnsupportedEncodingException e) {System.out.println("UnsupportedEncodingException");} catch (ParseException e) {System.out.println("ParseException");} catch (IOException e) {return "TimeOut";}return result;}/* *//*** 使用正則表達(dá)式過濾HTML標(biāo)記*//*private String filterHtml(String source) {if (null == source) {return "";}return source.replaceAll("</?[^>]+>", "").trim();}private void showToast(Context mContext, String message, int flag) {Looper.prepare();Toast.makeText(mContext, message, flag).show();Looper.loop();}*/}?
總結(jié)
以上是生活随笔為你收集整理的HttpURLConnection和HttpClient的简单用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成为一名JAVA高级工程师你需要学什么
- 下一篇: 5v2a可以给苹果充吗