java客户端HTTP请求工具类
程序员文章站
2024-03-14 15:12:52
...
整理HTTP请求工具类,便于今后项目中使用
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
public static String METHOD_GET = "Get";
public static String METHOD_POST = "Post";
public static String get(String url) {
HttpClient httpClient = new DefaultHttpClient();
// get method
HttpGet httpGet = new HttpGet(url);
//response
HttpResponse response = null;
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
//get response into String
String temp = "";
try {
HttpEntity entity = response.getEntity();
temp = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
public static String post(String url, String json) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}