关闭

Android 发送普通的post请求的方法

1224人阅读 评论(0) 收藏 举报
public static String sendRequest(Map<String,Object> params,String url){		
		String res=null;
		HttpEntity entity=null;
		HttpClient client=new DefaultHttpClient();
		HttpPost post=new HttpPost(url);
		List<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
		Set<Map.Entry<String,Object>> entrySet=params.entrySet();
		for(Map.Entry<String, Object> entry:entrySet){
			Log.i("test",entry.getKey()+"--"+entry.getValue());
			BasicNameValuePair bnv=new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue()));
			list.add(bnv);
		}
		
		try {
			post.setEntity(new UrlEncodedFormEntity(list));
			Log.i("test","before send request");
			HttpResponse response = client.execute(post);
			Log.i("test","after send request");
			Log.i("test",response.getStatusLine().getStatusCode()+"");
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				entity=response.getEntity();
				res=EntityUtils.toString(entity);
			}			
		} catch (ClientProtocolException e) {
			Log.i("test",e.getMessage());
		} catch (IOException e) {
			Log.i("test",e.getMessage());
		}finally{
			try {
				if(entity!=null){
					entity.consumeContent();
				}
				
				client.getConnectionManager().shutdown();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}	
		return res;
	}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:417872次
    • 积分:4862
    • 等级:
    • 排名:第5860名
    • 原创:96篇
    • 转载:5篇
    • 译文:1篇
    • 评论:85条
    最新评论