java使用httpclient封装post请求和get的请求

叁歲伎倆 2022-06-03 10:07 350阅读 0赞

package com.marco.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
* @author admin
* @date 2019年01月24日 下午2:49
* HttpClient工具类
*/
public class HttpUtil {

private static Logger logger = Logger.getLogger(HttpUtil.class);

/**
* get请求
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

  1. /\*\*请求发送成功,并得到响应\*\*/
  2. if (response.getStatusLine().getStatusCode() == HttpStatus.SC\_OK) \{
  3. /\*\*读取服务器返回过来的json字符串数据\*\*/
  4. String strResult = EntityUtils.toString(response.getEntity());
  5. return strResult;
  6. \}
  7. \}
  8. catch (IOException e) \{
  9. e.printStackTrace();
  10. \}
  11. return null;

}

/**
* post请求(用于key-value格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params){

BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));

  1. //设置参数
  2. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  3. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) \{
  4. String name = (String) iter.next();
  5. String value = String.valueOf(params.get(name));
  6. nvps.add(new BasicNameValuePair(name, value));
  7. //System.out.println(name +"-"+value);
  8. \}
  9. request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF\_8));
  10. HttpResponse response = client.execute(request);
  11. int code = response.getStatusLine().getStatusCode();
  12. if(code == 200)\{ //请求成功
  13. in = new BufferedReader(new InputStreamReader(response.getEntity()
  14. .getContent(),"utf-8"));
  15. StringBuffer sb = new StringBuffer("");
  16. String line = "";
  17. String NL = System.getProperty("line.separator");
  18. while ((line = in.readLine()) != null) \{
  19. sb.append(line + NL);
  20. \}
  21. in.close();
  22. return sb.toString();
  23. \}
  24. else\{ //
  25. System.out.println("状态码:" + code);
  26. return null;
  27. \}
  28. \}
  29. catch(Exception e)\{
  30. e.printStackTrace();
  31. return null;
  32. \}

}

/**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader(“Accept”, “application/json”);
httpPost.setHeader(“Content-Type”, “application/json”);
String charSet = “UTF-8”;
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;

  1. try \{
  2. response = httpclient.execute(httpPost);
  3. StatusLine status = response.getStatusLine();
  4. int state = status.getStatusCode();
  5. if (state == HttpStatus.SC\_OK) \{
  6. HttpEntity responseEntity = response.getEntity();
  7. String jsonString = EntityUtils.toString(responseEntity);
  8. return jsonString;
  9. \}
  10. else\{

logger.error(“请求返回:”+state+”(“+url+”)”);
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

}

发表评论

表情:
评论列表 (有 0 条评论,350人围观)

还没有评论,来说两句吧...

相关阅读