http post发送请求

时间:2023-03-10 07:17:56
http post发送请求
一:

用java自带URL发送
public synchronized JSONObject getJSON(String url2, String param) {
try {
URL url = new URL(url2);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true); //获取返回数据需要设置为true 默认false
con.setDoInput(true); //发送数据需要设置为true 默认false
con.setReadTimeout(5000);
con.setConnectTimeout(5000);
con.setRequestMethod("POST");
con.connect();
DataOutputStream out = new DataOutputStream(con.getOutputStream());
if (param != null) {
param = URLEncoder.encode(param,"utf-8");//url编码防止中文乱码
out.writeBytes(param);
}
out.flush();
out.close();
BufferedReader red = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer();
String line;
while ((line = red.readLine()) != null) {
sb.append(line);
}
red.close();
return JSONObject.fromObject(sb);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} 二:apache httppost方式 /**
* post请求,发送json数据
*
* @param url
* @param json
* @return
*/
public static JSONObject doPost(String url, String json) {
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json, "UTF-8"); // 中文乱码在此解决
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = HttpClients.createDefault().execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSON.parseObject(result);
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
} 三: httppost 发送map /**
* post请求
*
* @param url
* @param param
* @return
*/
public static String httpPost(String url, Map<String, Object> map) {
try {
HttpPost post = new HttpPost(url);
        //requestConfig post请求配置类,设置超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(50000).build();
post.setConfig(requestConfig);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null && entry.getValue() != "") {
              //用basicNameValuePair来封装数据
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
}
}
          //在这个地方设置编码 防止请求乱码
post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
GeneralLog.info(ModelName, "请求url:" + url);
GeneralLog.info(ModelName, "请求数据:" + map);
CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(post);
System.out.println("返回数据:" + httpResponse);
String result = null;
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);// 取出应答字符串
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}