文章目录
- 前言
- 一、使用 HttpURLConnection发送post请求
- 二、mian方法测试
前言
简单的记录一下 方便以后使用
一、使用 HttpURLConnection发送post请求
public class SSLHTTP {
public static String sendPost(JSONObject json, String URL) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result;
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line + "n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
}
二、mian方法测试
这里测试一下 请求百度
代码如下(示例):
JSONObject jsonObject = new JSONObject();
jsonObject.put("测试数据", "测试数据");
jsonObject.put("测试数据2", "测试数据2");
String url = "https://www.baidu.com/";
String result = SSLHTTP.sendPost(jsonObject, url);
System.out.println("返回数据:"+result);
请求成功
总结
很简单 就到这里了再见!!!



