关闭

HttpClient Post、get 请求方式

标签: httpclienthttpclient Posthttpclient get
498人阅读 评论(0) 收藏 举报
分类:

以下代码全部功能完善,并且亲测,线上正在使用,大家可以放心使用,如果有什么问题,可以给我留言。


package com.xhrd.dev.util.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientUtil {
/**
* 请求Http post类型URL

* @param url 请求Url
* @param map 请求参数
* @return
*/
    public static String fireHttpPost(String url,Map<String,Object> map){  


    String json = "";
    
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
Iterator iterator = map.entrySet().iterator();  
        while(iterator.hasNext()){  
            Entry<String,Object> elem = (Entry<String, Object>) iterator.next();              
            postMethod.addParameter(elem.getKey(), elem.getValue().toString());            
        } 
try {
int statusCode = client.executeMethod(postMethod);
if(statusCode == HttpStatus.SC_OK){
json = postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
    
    }
    
    
    
    /**
* 请求Http post类型URL

* @param url 请求Url
* @return
*/
    public static String fireHttpGet(String url){  
String json = "";    
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
try {
int statusCode = client.executeMethod(getMethod);
if(statusCode == HttpStatus.SC_OK){
json = getMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
    }
}

以上方法,一个为HttpClient  Post请求,一个为 HttpClient get 请求。


下载所需jar 包连接-------------->   点击下载


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:52760次
    • 积分:971
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:100篇
    • 译文:0篇
    • 评论:1条