HttpPoster接口调用

工作中经常用到的东西,这也是自己在公司的基础上改造的,感觉挺好用,分享一下
package com.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.mail.internet.HeaderTokenizer.Token;

import net.sf.json.JSONObject;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * Http Post
 * 调用远程接口
 * @author lxk
 * 
 */
public class HttpPoster{

	
	public String sendMap(String url,Map<String, Object> map){  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        String smsUrl=url;
        HttpPost httppost = new HttpPost(smsUrl);  
        String strResult = "";  
          
        try {  
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            	Set<Entry<String, Object>> set = map.entrySet();
                	for (Entry<String, Object> entry : set) {//循环map传递进来的参数,如有不理解可参看我之前发的博文
                		  nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));  
                	}
                httppost.addHeader("Content-type", "application/x-www-form-urlencoded");  
                httppost.setEntity( new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));  
                HttpResponse response = httpclient.execute(httppost);  
                if (response.getStatusLine().getStatusCode() == 200) {  
                    /*读返回数据*/  
                    String conResult = EntityUtils.toString(response  
                            .getEntity());
                    System.out.println("成功拿到返回数据");
                        return conResult;  
                } else {  
                    String err = response.getStatusLine().getStatusCode()+"";  
                    strResult += "接口通信失败:"+err;  
                }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        System.out.println("通信失败:"+strResult);
        return "error";  
    }  
}

猜你喜欢

转载自patronli.iteye.com/blog/2324156
今日推荐