1.错误代码,会出现400错误
public String test() {
SimpleDateFormat timeFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = timeFormat.format(new Date());
String body = "{}"; //请求json串
String contentType = "application/json";
// 创建httpclient对象
String result = null;
String url = "请求url";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHost proxy = new HttpHost("代理IP", 代理端口, "HTTP");
HttpPost httpPost = new HttpPost(url);
try { // 参数键值对
httpPost.setEntity(new StringEntity(body));
httpPost.setHeader("Content-Type", contentType);
HttpResponse response = httpClient.execute(proxy, httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpPost) {
// 释放连接
httpPost.releaseConnection();
}
}
return result;
}
2.经过修改后如下
public String test() {
SimpleDateFormat timeFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = timeFormat.format(new Date());
String body = "{}";
String contentType = "application/json";
// 创建httpclient对象
String result = null;
String url = "";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHost proxy = new HttpHost("代理IP地址", 代理端口, "HTTP");
HttpPost httpPost = new HttpPost(url);
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
try { // 参数键值对
httpPost.setEntity(new StringEntity(body))
httpPost.setHeader("Content-Type", contentType);
httpPost.setConfig(config);
HttpResponse response = httpClient.execute(proxy, httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpPost) {
// 释放连接
httpPost.releaseConnection();
}
}
return result;
}
或者可以使用okhttp
public String test2() {
Response response = null;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("代理地址", 代理端口));
builder.proxy(proxy);
OkHttpClient client = builder.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{请求json串}");
Request request = new Request.Builder()
.url("接口地址")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}