android http 连接

public class HttpClient {


	public static String sendHttpClientPost(String path,
			Map<String, String> map, String encode) {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (Map.Entry<String, String> 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);
			// 执行Post请求
			DefaultHttpClient client = new DefaultHttpClient();
			HttpResponse httpResponse = client.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				httpResponse.getEntity().getContent();
				return changInputStream(httpResponse.getEntity().getContent(),
						encode);
			}
			else{
				System.out.println("error");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";


	}


	public static String changInputStream(InputStream inputStream,String encode) {
		
		//将输入流变成字符串
		ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		byte[] data=new byte[1024];
		int len=0;
		String result="";
		try{
		if(inputStream!=null){
			while((len=inputStream.read(data))!=-1){
				byteArrayOutputStream.write(data,0,len);
				
			}
		}
		result=new String(byteArrayOutputStream.toByteArray(),encode);
		}catch(Exception e){
			
		}
		
		return result;
	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String path="http://10.118.163.171/http/HttpServlet";
		Map<String, String> params = new HashMap<String, String>();
		params.put("name", "admin");
		params.put("pwd", "199273");
		String result = sendHttpClientPost(path, params, "utf-8");
		System.out.println("--result-->" + result);
	}


}

你可能感兴趣的:(android http 连接)