java后台http请求方式

长时间没有写这方面的代码,突然提笔对于http的请求方式代码不知道如何下手,特此记录一下

 
 
public JSONObject  doPost(String url) throws IOException {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);

postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//添加请求参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("url", "www.baidu.com");
RequestEntity se = new StringRequestEntity(jsonObject.toString(), "application/json", "utf-8");
postMethod.setRequestEntity(se);
httpClient.executeMethod(postMethod);
String responseMsg = postMethod.getResponseBodyAsString().trim();
JSONObject returnJson = JSONObject.parseObject(responseMsg);
return returnJson;
}
 

http请求方式有多种,参考链接:https://www.cnblogs.com/hhhshct/p/8523697.html

猜你喜欢

转载自www.cnblogs.com/qingpw/p/12902286.html
今日推荐