近日做了个接口需求,要求把json数据放入文件中,以文件的形式发送http报文请求,在网上找了好多种方式,都没能联调成功,最终用了OkHttpClient才实现了。
测试如下
util工具类
直接复制过去即可,什么都不用改。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OkHttpUtil {
public static class SSLSocketFactoryImp extends SSLSocketFactory {
private SSLContext sslContext = SSLContext.getInstance("SSL");
private TrustManager trustManager = null;
public SSLContext getSSLContext() {
return sslContext;
}
public X509TrustManager getTrustManager() {
return (X509TrustManager) trustManager;
}
public SSLSocketFactoryImp(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException {
super();
trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
};
sslContext.init(null, new TrustManager[]{trustManager}, null);
}
@Override
public String[] getDefaultCipherSuites() {
return new String[0];
}
@Override
public String[] getSupportedCipherSuites() {
return new String[0];
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
@Override
public Socket createSocket(Socket socket, String host, int post, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, post, autoClose);
}
@Override
public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
return null;
}
@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException {
return null;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i) throws IOException {
return null;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException {
return null;
}
}
public static OkHttpClient getClient(Interceptor... interceptor) {
OkHttpClient.Builder builder = null;
try {
builder = new OkHttpClient.Builder();
KeyStore trustStore;
trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactoryImp ssl = new SSLSocketFactoryImp(KeyStore.getInstance(KeyStore.getDefaultType()));
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
builder.sslSocketFactory(ssl.getSSLContext().getSocketFactory(), ssl.getTrustManager())
.hostnameVerifier(DO_NOT_VERIFY);
} catch (Exception e) {
}
return builder.build();
}
}
Junit测试
public class haha{
public static void main(String[] args) {
String APIUrl = "xxxxxxxxxxxx";
String URL = "https://" + "xxx.xxx.xxx.xx" + ":" + "xxxx" + APIUrl;
String username = "xxx";
String pwd = "xxx";
JSONObject json = new JSONObject();
json.put("userName",username);
json.put("password",pwd);
JSONObject job = doFilePost(json,URL);
System.out.println("调用认证接口:"+job);
}
public static JSONObject doFilePost(JSONObject params,String url){
try {
File file = new File("file/post_request.json");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
write.write(params.toJSONString());
write.flush();
write.close();
OkHttpClient client = getClient();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("filename", file.getPath(),
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(file.getPath())))
.build();
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.addHeader("Accept-Language", "zh-cn")
.addHeader("Cookie", "SESSIONID=765c194a6ab8b92845717cc4033a024d; C_HASH=605DA24B")
.build();
Response response = client.newCall(request).execute();
JSONObject job = JSON.parseObject(response.body().string());
return job;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|