okhttp工具类对应jdk1.7、1.8不通版本上传附件以及参数代码处理逻辑

java  jdk1.7版本,对应okhttp版本为2.0

需要导入的jar包,注意,这里边包含有https处理,不需要刻意去掉

okhttp工具类对应jdk1.7、1.8不通版本上传附件以及参数代码处理逻辑_第1张图片

package nc.itf.vams.util;

import java.io.IOException;

import java.security.SecureRandom;

 

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import java.util.HashMap;

import java.util.Map;

 

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.SSLSocketFactory;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

 

import org.json.JSONObject;

 

import com.squareup.okhttp.FormEncodingBuilder;

import com.squareup.okhttp.Headers;

import com.squareup.okhttp.MediaType;

import com.squareup.okhttp.MultipartBuilder;

import com.squareup.okhttp.OkHttpClient;

import com.squareup.okhttp.Request;

import com.squareup.okhttp.RequestBody;

import com.squareup.okhttp.Response;

import com.squareup.okhttp.ResponseBody;

同步参数代码

 /**
    * 
    * @param tokenURL
    * @param username
    * @param password
    * @param oauthKey
    * @param oauthSecret
    * @param scope
    * @return
    * @throws Exception

    * 获取token
    * 
    *
    */
   public String getToken(String tokenURL,String username,String password,String oauthKey,String oauthSecret,String scope) throws Exception{
	   OkHttpClient client = new OkHttpClient();

        //createSSLSocketFactory,该方法是处理https使用,可以不用
	   client.setSslSocketFactory(createSSLSocketFactory());
	   
       
	   Map formBody = new HashMap();//创建表单请求体
	    formBody.put("grant_type", "password");//传递键值对参数
	    formBody.put("username", username);//传递键值对参数
	    formBody.put("password", password);//传递键值对参数
	    formBody.put("client_id", oauthKey);//传递键值对参数
	    formBody.put("client_secret", oauthSecret);//传递键值对参数
	    formBody.put("scope", scope);//传递键值对参数
        FormEncodingBuilder multipartBuilder=new FormEncodingBuilder();
        for (String key : formBody.keySet()) {
        	multipartBuilder.add(key,formBody.get(key));
        }
        RequestBody requestBody=multipartBuilder.build();
	    Request request = new Request.Builder()//创建Request 对象。
	            .url(tokenURL)
	            .post(requestBody)//传递请求体
	            .build();
	    
	    Response response = client.newCall(request).execute();
	    
//	    int code = response.code();//获取响应码
//        String message = response.message();//获取响应消息      
//        InputStream inputStream = body.byteStream();//获取输入流
//        byte[] bytes = body.bytes();//获取字节数组
	    ResponseBody  body = response.body();//获取响应体
        String str = body.string();//获取字符串数据
        JSONObject json=new JSONObject(str);
		String access_token=json.getString("access_token");
		String token_type=json.getString("token_type");
		String token = token_type + " " + access_token;
        return token;
	   
   }

 

上传附件代码,对应okhttp版本为2.0

	private static final String Charset_UTF = "UTF-8";
	
	private static MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/octet-stream; charset=utf-8");

	/**
	 * 
	 * @param url
	 * @param fileFlow
	 * @param token
	 * @return
	 * @throws RestClientException
	 * @throws IOException
	 * 
	 * 执行数据交换
	 */
   public static String createMultiPart(String url,byte[] fileFlow,String xml,String token,String parameterFile
		   	) throws Exception {
        OkHttpClient client = new OkHttpClient();
        
        client.setSslSocketFactory(createSSLSocketFactory());
        client.setHostnameVerifier(new TrustAllHostnameVerifier());
        
        RequestBody bodyMessagePayload=RequestBody.create(MEDIA_TYPE_MARKDOWN, fileFlow);
        RequestBody bodyParameterRequest=RequestBody.create(MediaType.parse("application/json"), parameterFile.getBytes("UTF-8"));
       
        MultipartBuilder multipartBuilder=new MultipartBuilder();
        multipartBuilder.type(MultipartBuilder.FORM);
        
        String[] fileKeys=new String[]{"ParameterRequest","MessagePayload"};
        String[] fileName=new String[]{"MessageParameters","messageId"};
        RequestBody[] fileBody=new RequestBody[]{bodyParameterRequest,bodyMessagePayload};
        for (int i = 0; i < fileKeys.length; i++) {
        	multipartBuilder.addPart(Headers.of("Content-Disposition",
                    "form-data; name=\"" + fileKeys[i] + "\"; fileName=\"" + fileName[i] + "\""),
            fileBody[i]);
		}
//   	multipartBuilder.addPart(Headers.of("Content-Disposition",
//           "form-data; name=\"ParameterRequest\"; fileName=\"MessageParameters\""),
//           bodyParameterRequest).addPart(Headers.of("Content-Disposition",
//           "form-data; name=\"MessagePayload\"; fileName=\"messageId\""),
//           bodyMessagePayload);
        
        RequestBody requestBody=multipartBuilder.build();
                
        Request request = new Request.Builder()
                .header("Authorization", token)
                .header("X-TenantId", "infor")
                .header("Content-Type", "multipart/form-data" + ";charset="+Charset_UTF)
                .url(url)
                .post(requestBody)
                .build();
        
        Response response = client.newCall(request).execute();
        
//        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//        int code = response.code();//获取响应码
//        String message = response.message();//获取响应消息       
//        InputStream inputStream = body.byteStream();//获取输入流
//        byte[] bytes = body.bytes();//获取字节数组
        ResponseBody  body = response.body();//获取响应体
        String str = body.string();//获取字符串数据
        return str;
    }

 

 

java  jdk1.8及以上版本,对应okhttp版本为3.0

需要导入的jar包

import okhttp3.*;

同步参数代码

  /**
    * 
    * @param tokenURL
    * @param username
    * @param password
    * @param oauthKey
    * @param oauthSecret
    * @param scope
    * @return
    * @throws Exception

    * 获取token
    * 
    *
    */
   public String getToken(String tokenURL,String username,String password,String oauthKey,String oauthSecret,String scope) throws Exception{
	   
	   FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
	    formBody.add("grant_type", "password");//传递键值对参数
	    formBody.add("username", username);//传递键值对参数
	    formBody.add("password", password);//传递键值对参数
	    formBody.add("client_id", oauthKey);//传递键值对参数
	    formBody.add("client_secret", oauthSecret);//传递键值对参数
	    formBody.add("scope", scope);//传递键值对参数
	    
	    // 这里也是放了https处理,可以不使用直接OkHttpClient client =new OkHttpClient();
	    OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(createSSLSocketFactory())
        		.hostnameVerifier(new TrustAllHostnameVerifier()).build();
	    
	    Request request = new Request.Builder()//创建Request 对象。
	            .url(tokenURL)
	            .post(formBody.build())//传递请求体
	            .build();
	    
	    Response response = client.newCall(request).execute();
	    
//	    int code = response.code();//获取响应码
//        String message = response.message();//获取响应消息      
//        InputStream inputStream = body.byteStream();//获取输入流
//        byte[] bytes = body.bytes();//获取字节数组
	    ResponseBody  body = response.body();//获取响应体
        String str = body.string();//获取字符串数据
        JSONObject json=new JSONObject(str);
		String access_token=json.getString("access_token");
		String token_type=json.getString("token_type");
		String token = token_type + " " + access_token;
        return token;
	   
   }

上传附件代码,对应okhttp版本为3.0

private static final String Charset_UTF = "UTF-8";
	
	private static MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/octet-stream; charset=utf-8");

	/**
	 * 
	 * @param url
	 * @param fileFlow
	 * @param token
	 * @return
	 * @throws RestClientException
	 * @throws IOException
	 * 
	 * 执行数据交换
	 */
   public static String createMultiPart(String url,byte[] fileFlow,String xml,String token,String parameterFile
		   	) throws Exception {
        OkHttpClient client = new OkHttpClient();
        
        client.setSslSocketFactory(createSSLSocketFactory());
        client.setHostnameVerifier(new TrustAllHostnameVerifier());
        
        RequestBody bodyMessagePayload=RequestBody.create(MEDIA_TYPE_MARKDOWN, fileFlow);
        RequestBody bodyParameterRequest=RequestBody.create(MediaType.parse("application/json"), parameterFile.getBytes("UTF-8"));
       
        MultipartBuilder multipartBuilder=new MultipartBuilder();
        multipartBuilder.type(MultipartBuilder.FORM);
        
        String[] fileKeys=new String[]{"ParameterRequest","MessagePayload"};
        String[] fileName=new String[]{"MessageParameters","messageId"};
        RequestBody[] fileBody=new RequestBody[]{bodyParameterRequest,bodyMessagePayload};
        for (int i = 0; i < fileKeys.length; i++) {
        	multipartBuilder.addPart(Headers.of("Content-Disposition",
                    "form-data; name=\"" + fileKeys[i] + "\"; fileName=\"" + fileName[i] + "\""),
            fileBody[i]);
		}
//   	multipartBuilder.addPart(Headers.of("Content-Disposition",
//           "form-data; name=\"ParameterRequest\"; fileName=\"MessageParameters\""),
//           bodyParameterRequest).addPart(Headers.of("Content-Disposition",
//           "form-data; name=\"MessagePayload\"; fileName=\"messageId\""),
//           bodyMessagePayload);
        
        RequestBody requestBody=multipartBuilder.build();
                
        Request request = new Request.Builder()
                .header("Authorization", token)
                .header("X-TenantId", "infor")
                .header("Content-Type", "multipart/form-data" + ";charset="+Charset_UTF)
                .url(url)
                .post(requestBody)
                .build();
        
        Response response = client.newCall(request).execute();
        
//        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//        int code = response.code();//获取响应码
//        String message = response.message();//获取响应消息       
//        InputStream inputStream = body.byteStream();//获取输入流
//        byte[] bytes = body.bytes();//获取字节数组
        ResponseBody  body = response.body();//获取响应体
        String str = body.string();//获取字符串数据
        return str;
    }

 

你可能感兴趣的:(java,post)