使用sendPost1方法请求报500 直接抛出异常
使用doPostSoap方法也会报500但是会返回错误信息
使用sendPost1方法怎么能获取到和doPostSoap一样的结果?
public static String sendPost1(String path, Map param) throws IOException {
String result="";
// 创建url资源
URL url = new URL(path);
// 建立http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置不用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
String token = getToken();
conn.setRequestProperty("token",token);
//转换为字节数组
String param_str = JSONObject.toJSONString(param);
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 开始连接请求
conn.connect();
OutputStream out = conn.getOutputStream();
// 写入请求的字符串
out.write((param_str.toString()).getBytes());
out.flush();
out.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
System.out.println(conn.getRequestMethod());
```java
// 请求返回的状态
```java if (conn.getResponseCode() == 200) { ```
System.out.println("连接成功");
// 请求返回的数据
InputStream in = conn.getInputStream();
String a = null;
try {
byte[] data1 = new byte[in.available()];
in.read(data1);
// 转成字符串
a = new String(data1);
System.out.println(a);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
System.out.println("no++");
}
return result;
}
public static String doPostSoap(String postUrl, Map map) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000).build();
httpPost.setConfig(requestConfig);
try {
String token = getToken();
httpPost.setHeader("token", token);
StringEntity data = new StringEntity(JSONObject.toJSONString(map),Charset.forName("UTF-8"));
data.setContentEncoding("UTF-8");
data.setContentType("application/json");
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
System.err.println("获取返回信息,post请求,返回的 状态码:" + statusCode);
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
//System.out.println("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
System.out.println(e);
}
return retStr;
}
获取请求返回的数据,返回状态不是200就执行不了下面的代码。把下面代码放在判断外面。
// 请求返回的数据
InputStream in = conn.getInputStream();
String a = null;
try {
byte[] data1 = new byte[in.available()];
in.read(data1);
// 转成字符串
a = new String(data1);
System.out.println(a);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}