精华内容
下载资源
问答
  • android---用okHttp提交Form表单

    千次阅读 2017-03-02 09:46:11
    FormBody requestBody = new FormBody.Builder().add("", ).add("", ).add("", ).build(); Request request = new Request.Builder().url(url).header("Authorization", "Bearer "+token).patch(requestBody).bu
    FormBody requestBody = new FormBody.Builder().add("", ).add("", ).add("", ).build();
        Request request = new Request.Builder().url(url).header("Authorization", "Bearer "+token).patch(requestBody).build();
    展开全文
  • OkHttpClient client = new OkHttpClient(); RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);//将file转换成RequestBody文件 RequestBody requestBody = new MultipartBody....
    
           
          OkHttpClient client = new OkHttpClient();
    
              File fileByPath = new File(paasSearchBitmapPath);
    
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);//将file转换成RequestBody文件
            RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("co_id", "333")//# 合作⽅方标识id
                    .addFormDataPart("id", “333”)//# 随机⽣生成的字符串串
                    .addFormDataPart("submit_key", key)//# 验证信息,b64encode(rc4_encrypt(data=id,key=CO_KEY))
                    .addFormDataPart("pic", "head_image", fileBody).build();
            Request request = new Request.Builder().url("http://test.api")
                    .post(requestBody).build();
    
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (netCallBack != null) {
                        netCallBack.onFail(e.getMessage());
                    }
                    Log.e("tu", "getPayOrder_onFailure" + e.getMessage());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        if (netCallBack != null) {
                            netCallBack.onSuccess(string);
                        }
                        Log.e("tu", "getPayOrder" + string);
                    }
                }
            });

     

    展开全文
  • okhttp3 表单上传文件

    千次阅读 2019-01-24 19:37:21
    1、maven的pom.xml文件中添加okhttp3的依赖: <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <ver...

    1、maven的pom.xml文件中添加okhttp3的依赖:

            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.6.0</version>
            </dependency>

    2、java代码:

     这里主要注意中文乱码问题的处理以及跳过ssl认证问题的处理

    import java.io.File;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.concurrent.TimeUnit;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    
    public class UploadUtils {
    	
    	public static void uploadFile(){
    	    String path = "https://192.168.1.1:8080/upload/file";      //上传接口
    	    OkHttpClient client = getUnsafeOkHttpClient();          //设置跳过所有ssl认证
    	    File file = new File("C:\\xxxxx");           //要上传的文件路径
    	    
    	    RequestBody fileBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8") , file); 
    	    String name = "fileName";          //文件名称
    	    try {
    		name = URLEncoder.encode(name, "UTF-8");                 //文件名称编码,防止出现中文乱码
    	    } catch (UnsupportedEncodingException e1) {
    		//TODO
    	    }
    	
    	    //定义请求体,前面三个为表单中的string类型参数,第四个为需要上传的文件
    	    MultipartBody mBody = new MultipartBody.Builder().setType(MultipartBody.FORM) 
    	            .addFormDataPart("fileSize" , "12123")                
    	            .addFormDataPart("time" , "234234") 
    	            .addFormDataPart("name" , name) 
    	            .addFormDataPart("file" , name , fileBody)
    	            .build();  
    		
    	    //设置为post请求,url后面为请求路径,header设置请求头(可以设置多个),post后面设置请求体
                Request request = new Request.Builder().url(path).header("xxxx","xxxx").post(mBody).build();
                //执行请求操作
                try {
                    Response response = client.newCall(request).execute();
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        System.out.println("获取到的响应信息为: "+result);
                    }
                    response.body().close();
                } catch (Exception e) {
            	//TODO
                }
    	}
    	
    	public static OkHttpClient getUnsafeOkHttpClient() { 
    		try { 
    			final TrustManager[] trustAllCerts = new TrustManager[]{
    					 new X509TrustManager() {
    							@Override
    							public void checkClientTrusted(X509Certificate[] chain,
    									String authType) throws CertificateException {
    								// TODO Auto-generated method stub
    								
    							}
    							@Override
    							public void checkServerTrusted(X509Certificate[] chain,
    									String authType) throws CertificateException {
    								// TODO Auto-generated method stub
    							}
    							@Override
    							public X509Certificate[] getAcceptedIssuers() {
    								// TODO Auto-generated method stub
    								return new X509Certificate[]{};
    							}
    				         }
    			}; 
    			final SSLContext sslContext = SSLContext.getInstance("SSL"); 
    			sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); 
    			final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); 
    			OkHttpClient.Builder builder = new OkHttpClient.Builder()
    				.connectTimeout(500, TimeUnit.MILLISECONDS)
    			    .readTimeout(500, TimeUnit.MILLISECONDS);
    			builder.sslSocketFactory(sslSocketFactory); 
    			builder.hostnameVerifier(new HostnameVerifier() { 
    				@Override
    				public boolean verify(String arg0, SSLSession arg1) {
    					// TODO Auto-generated method stub
    					return true;
    				} 
    				}); 
    			return builder.build(); 
    		} catch (Exception e) { 
    			//TODO
    			throw new RuntimeException(e); 
    		} 
    	}
    	
    	/*	
    	 * 	private static File converMultipartFileToFile(MultipartFile multipartFile){    //将MultipartFile格式对象转File
    		File file = null;
    		try {
    			file = File.createTempFile("tmp", null);
    	    	multipartFile.transferTo(file);
    	    	file.deleteOnExit();        
    		} catch (Exception e) {
    	    	e.printStackTrace();
    		}
    		return file;
    	}*/
    }
    

     

    展开全文
  • RxJava实战演示3----okhttp3表单提交

    千次阅读 2016-07-26 15:15:16
    1.定义LoginUtils public class LoginUtils { private OkHttpClient client; public LoginUtils() { client = new OkHttpClient(); } ... * 定义了login操作,使用RxAndroid的编程思想 * @pa

    1.定义LoginUtils

    public class LoginUtils {
    
        private OkHttpClient client;
    
        public LoginUtils() {
            client = new OkHttpClient();
        }
    
        /**
         * 定义了login操作,使用RxAndroid的编程思想
         * @param url
         * @param params
         * @return
         */
        public Observable<String> login(String url,Map<String,String> params){
            return Observable.create(new Observable.OnSubscribe<String>() {
                @Override
                public void call(Subscriber<? super String> subscriber) {
                   if (!subscriber.isUnsubscribed()){
                       FormBody.Builder builder = new FormBody.Builder();
                       if (params!=null&&!params.isEmpty()){
                           for(Map.Entry<String,String> entry:params.entrySet()){
                               builder.add(entry.getKey(),entry.getValue());
                           }
                       }
                       RequestBody requestBody = builder.build();
                       //构建post请求
                       Request request = new Request.Builder().url(url).post(requestBody).build();
                       client.newCall(request).enqueue(new Callback() {
                           @Override
                           public void onFailure(Call call, IOException e) {
                               subscriber.onError(e);
                           }
    
                           @Override
                           public void onResponse(Call call, Response response) throws IOException {
                              if (response.isSuccessful()){
                                  subscriber.onNext(response.body().string());
                              }
                               subscriber.onCompleted();//访问结束
                           }
                       });
                   }
                }
            });
        }
    }
    
    2.主页面调用

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("username", username.getText().toString().trim());
                    params.put("password", password.getText().toString().trim());
    
                    utils.login(LOGIN, params).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {
                           // dialog.dismiss();
                        }
    
                        @Override
                        public void onError(Throwable e) {
                            Log.i(TAG, e.getMessage());
                        }
    
                        @Override
                        public void onNext(String s) {
                            dialog.show();
                           // Log.i(TAG,s);
                           if (new JSONObject(json).getJSONObject("result").getInt("resultCode")==1){
                               //Log.i(TAG,"success");页面跳转
                           }
                        }
                    });
                }
            });



    展开全文
  • OKHttpForm表单修改请求编码的问题

    千次阅读 2017-02-08 11:23:36
    因Form表单提交OKHttp里有个 FormBody,但是呢FormBody里的是默认用utf-8编码发送的不能修改public final class FormBody extends RequestBody { private static final MediaType CONTENT_TYPE = MediaType....
  • 使用okhttp3 提交表单不会造成中文乱码问题,使用HttpURLConnection提交服务端收到会有乱码问题,这个还未想到解决办法 okhttp3的异常需要设置监听器, client.newCall(request).enqueue(object: Callback{ override...
  • OKhttp 表单

    2017-09-08 10:11:49
    JSON提交 package com.ceair.idoc; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; ...
  •  OkHttp3异步POST请求和OkHttp2有一些差别就是没有FormEncodingBuilder这个类,替代它的是功能更加强大的FormBody,具体使用如下:   private OkHttpClient client = new OkHttpClient(); public void ...
  • okhttp模拟表单(form)发送post请求

    千次阅读 2020-08-12 18:45:55
    直接上代码 //请求参数 Page<Map<String, Object>> virtualDataEngine = fwDimService.findParentList("VIRTUAL_DATA_ENGINE", "", getPageable()); if (virtualDataEngine.getSize() == 0) { ...
  • 2、post请求提交图片,带参数,表单形式提交图片。 与常规请求参数要求不同,记录一下。 原理:将post参数拼接到url中,json或者表单在添加的时候注明头文件。 0、 public static OkHttpClient sOkHttpClient ...
  • android okhttp实例

    2017-05-11 15:16:47
    这是一个用okhttp进行网络请求的例子,例子... - okhttp 提交表单 - okhttp 提交文件 - okhttp 下载文件 - okhttp https请求相关 尽量用简单易懂的编码方式,来实现一些常用的网络请求,分享出来希望对大家有帮助。
  • 一、Body 名称 类型 name string age string 二、实例展示 ... //通过FormBody对象构建Builder来添加表单参数 FormBody mFormBody = new FormBody.Builder() .add("name","彭老希") .add
  • OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据 我们这片博文就来聊聊这个反响很不错的OkHttp了,标题是我恶搞的,本篇将着重详细的分析,探索OkHttp这个框架的使用和...
  • OKHTTP3的简单使用 使用okhttp3需引入以下依赖 compile 'com.squareup.okio:okio:1.13.0' compile 'com.squareup.okhttp3:okhttp:3.9.0' 1.okhttp GET方式请求 //创建OkHttpClient对象 OkHttpClient
  • Okhttp

    2018-03-06 09:44:50
    okhttp
  • 1.文件上传,post提交表单  1.1表单提交需要用到 post,put方法,以方法体的方式组件表单信息。 RequestBody requestBody = new RequestBody() .type(RequestBody.FORM) .addParam("file", RequestB...
  • OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据 我们这片博文就来聊聊这个反响很不错的OkHttp了,标题是我恶搞的,本篇将着重详细的分析,探索OkHttp这个框架的使用和...
  • OkHttp

    2017-01-03 16:16:17
    OkHttp 当前最火Http框架, 由,Square公司推出, OKHttp的项目地址:https://github.com/square/okhttp特点 创建连接池缓存响应数据来减少重复的网络请求 基于Http的文件上传 文件下载 加载图片 支持SPDY, Google...
  • FormBody form = new FormBody.Builder() // 添加参数的键值对 .add("yl_jobId", json.getString("yl_jobId")) .add("public_key", json.getString("public_key")) .add("timestamp", json.getString(...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,836
精华内容 1,134
关键字:

okhttp提交表单