Android应用开发--Http

本文详细介绍了如何使用JDK中的HttpURLConnection及Apache的HttpClient进行HTTP Get和Post请求的发送与接收,包括了设置请求头、处理响应数据的具体实现,并提供了设置超时时间的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:JDK中HttpURLConnection

Get

URL url = new URL("string url"):
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
    strBuffer.append(line);
}
result = strBuffer.toString();
if (connection != null) {
    connection.disconnect();
}
if (in != null) {
  try {
     in.close();
  } catch (IOException e) {
     e.printStackTrace();
  }
}
Post

public String executeHttpPost() {
    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL("string url");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
		
		//写入参数
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes("token=xxxxxxx");
        dop.flush();
        dop.close();
        
		in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
    }
    if (in != null) {
        try {
        in.close();
        } catch (IOException e) {
        e.printStackTrace();
        }
        }
    }
    return result;
}

URLDecoder.decode("测试","utf-8");
URLEncoder.encode("测试","utf-8")

二:Apache的HttpClient

Get

HttpGet get=new HttpGet("str url?name=xxx&pwd=xxx");  
HttpClient cliet=new DefaultHttpClient();  
try {  
    HttpResponse response=cliet.execute(get);  
    HttpEntity entity=response.getEntity();  
    InputStream is=entity.getContent();  
    BufferedReader br=new BufferedReader(new InputStreamReader(is));  
    String line=null;  
    StringBuffer sb=new StringBuffer();  
    while((line=br.readLine())!=null){  
        sb.append(line);  
    }  
    System.out.println(sb.toString());  
} catch (ClientProtocolException e) {  
    e.printStackTrace();  
} catch (IOException e) {  
    e.printStackTrace();  
} 



Post

//创建默认的客户端对象  
HttpClient cliet=new DefaultHttpClient();  
//用list封装要向服务器端发送的参数  
List<BasicNameValuePair> pairs=new ArrayList<BasicNameValuePair>();  
pairs.add(new BasicNameValuePair("name", "xxx")); 
pairs.add(new BasicNameValuePair("pwd", "xxx"));   
try {  
    //用UrlEncodedFormEntity来封装List对象  
    UrlEncodedFormEntity urlEntity=new UrlEncodedFormEntity(pairs);  
    //设置使用的Entity  
    post.setEntity(urlEntity);  
    try {  
        //客户端开始向指定的网址发送请求  
        HttpResponse response=cliet.execute(post);  
        //获得请求的Entity  
        HttpEntity entity=response.getEntity();  
        InputStream is=entity.getContent();  
        //下面是读取数据的过程  
        BufferedReader br=new BufferedReader(new InputStreamReader(is));  
        String line=null;  
        StringBuffer sb=new StringBuffer();  
        while((line=br.readLine())!=null){  
            sb.append(line);  
        }  
        System.out.println(sb.toString());  
    } catch (ClientProtocolException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
} catch (UnsupportedEncodingException e) {  
    e.printStackTrace();  
} 

三- 超时Sample

<span style="color:#404040;">private class XmlAsyncLoader extends XmlResourceRequest {  
  
 private boolean mIsCancle = false;  
 private HttpGet mGet;  
 private HttpClient mHttp;  
  
 public XmlAsyncLoader(MxActivity<?> activity, String url)  
 throws MalformedURLException {  
 super(activity, url);  
 }  
  
 @Override  
 protected void doTaskInBackground() {  
 // 请求数据  
 if (mUrl.toLowerCase().startsWith("http://")) {  
 mGet = initHttpGet(mUrl);  
 mHttp = initHttp();  
 try {  
 HttpResponse response = mHttp.execute(mGet);  
 if (mIsCancle) {  
 return;  
 }  
 if (response != null) {  
 if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){  
 onResponseError("network error");  
 Log.v(TAG, "the code is :"+response.getStatusLine().getStatusCode());  
 return;  
 }  
 notifyUpdateProgress(70);  
 Document doc = getDocumet(response);  
 Element root = doc.getDocumentElement();  
 NodeList appList = root  
 .getElementsByTagName(Item_ELEMENT_NAME);  
 final int len = appList.getLength();  
 if (len <= 0) {// 没有items  
 onFoundNoItems();  
 return;  
 }  
 for (int i = 0; i < len; i++) {  
 Element item = (Element) appList.item(i);  
 if (item.getNodeType() == Node.ELEMENT_NODE) {  
 HahaItemInfo info = createHahaItemIno(item);  
 if (mIsCancle){  
 return;  
 }  
 onFoundItem(info, 80 + 20 * (i + 1) / len);  
 addUrlToQueue(info.userIconUrl);  
 }  
 };  
   
 }  
 }catch(ConnectTimeoutException e){  
 onResponseError("time out");  
 } catch (ClientProtocolException e) {  
 --mCurrentPage;  
 e.printStackTrace();  
 } catch (IOException e) {  
 --mCurrentPage;  
 e.printStackTrace();  
 } catch (XmlPullParserException e) {  
 --mCurrentPage;  
 e.printStackTrace();  
 }finally{  
 notifyLoadFinish();  
 notifyLoadImages();  
 mHttp.getConnectionManager().shutdown();  
 }  
  
 }  
 }  
  
  
 private HttpClient initHttp() {  
 HttpClient client = new DefaultHttpClient();  
</span><span style="color:#cc0000;"> client.getParams().setIntParameter(  
 HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置  
 client.getParams().setIntParameter(  
 HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时  </span><span style="color:#404040;">
 return client;  
 }  
  
 private HttpGet initHttpGet(String mUrl) {  
 HttpGet get = new HttpGet(mUrl);  
 initHeader(get);  
 return get;  
 }  
  
  
 @Override  
 public boolean tryCancel() {  
 Log.i(TAG, "tryCanle is working");  
 mGet.abort();  
 mIsCancle = true;  
 mHttp.getConnectionManager().shutdown();  
 notifyLoadFinish();  
 return true;  
 }  
  
 }  </span>


URLEncoder.encode("测试","utf-8")
2 URLDecoder.decode("测试","utf-8");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值