Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android使用apache httpclient發送post請求

android使用apache httpclient發送post請求

編輯:關於Android編程

package com.liuc;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpPostUtil {

	public static String sendHttpPost(Map map,String encode,String path){
		
		List list=new ArrayList();
		if (map!=null&&!map.isEmpty()) {
			for(Map.Entry entry:map.entrySet()){
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		try {
			//實現將參數封裝到表單中,也就是請求體重
			UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,encode);
			//使用post方式提交數據
			HttpPost httpPost=new HttpPost(path);
			httpPost.setEntity(entity);
			RequestConfig requestConfig = RequestConfig.custom().
					setSocketTimeout(2000).setConnectTimeout(2000).build();//4.3之後的設置請求和傳輸超時時間
			httpPost.setConfig(requestConfig);
			//執行post請求
			//3.X是這樣的
			//HttpClient httpClient=new DefaultHttpClient();
			//4.x是這樣的
			HttpClient httpClient = HttpClients.createDefault();
			HttpResponse httpResponse=httpClient.execute(httpPost);
			
			if (httpResponse.getStatusLine().getStatusCode()==200) {
				return getStringForInputStream(httpResponse.getEntity().getContent(),encode);
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return path;
		
	}

	private static String getStringForInputStream(InputStream inputStream,
			String encode) {
		ByteArrayOutputStream stream=new ByteArrayOutputStream();
		byte[] data=new byte[1024];
		int len=0;
		String result=;
		try {
			if (inputStream != null) {
				while ((len = inputStream.read(data)) != -1) {
					stream.write(data, 0, len);
				}
				result=new String(stream.toByteArray(),encode);
			}
		} catch (Exception e) {
		}
		return result;
	}

}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved