FreeCMS商业版

功能强大、开源、代码通俗易懂、注释详细、面向二次开发友好!

承接网站建设、软件开发、微信开发项目,价格从优,欢迎咨询合作!

FreeCMS商业版V2.8已发布!购买请联系客服QQ 124812878 查看更新日志



在线演示 立即购买 下载免费版 下载商业版用户手册
客服QQ: 124812878 联系电话: 18339991503 Email: freeteam@foxmail.com

okhttp 使用 post - Ctrl+C&Ctrl+V - ITeye博客

加入收藏夹】     【打印】     【关闭】 来源: 日期:2018-02-08 11:43:17 点击量: 收藏

 

java  okhttp maven pom

 

<dependency>
<groupId>com.squareup.okhttp3<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/groupId>
<artifactId>okhttp<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/artifactId>
<version>3.2.0<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/version>
<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/dependency>
<dependency>
<groupId>com.squareup.okio<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/groupId>
<artifactId>okio<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/artifactId>
<version>1.7.0<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/version>
<http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/dependency>

 

 

 

OkhttpUtils.java

 

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.RespEntity;
import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.RespEnums;
import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.ValidatorUtil;
 
public class OkhttpUtils { 

	public static RespEntity postPipe(String url,   Map<String, Object> params) {
		RespEntity entity = new RespEntity("");
		  RequestBody requestBody = new RequestBody( ) {
				@Override
				public MediaType contentType() { 
					return  MediaType.parse("applicationhttp:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/json;charset:UTF-8");
				}

				@Override
				public void writeTo(BufferedSink sink) throws IOException {
					sink.writeUtf8(FastJsonUtils.toJSONString(params));
				}
				  
			  };
			  
			  Request request = new Request.Builder()
		        .url(url)
		        .post(requestBody)
		        .build();
			  OkHttpClient client = new OkHttpClient();
			  Response response  = null;
			  try {
				  response = client.newCall(request).execute();
			} catch (IOException e) { 
				e.printStackTrace();
				entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
				entity.setMsg(e.getMessage());
			}
			  
			  if (!response.isSuccessful()) {
				  entity.setCode(RespEnums.RESP_OTHER_RESP_CODE.getCode()); 
				}
				String result = null;
				try {
					result = response.body().string();
					entity.setData(result);
				} catch (IOException e) {
					e.printStackTrace();
					entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
					entity.setMsg(e.getMessage());
				} 
		return entity;
	}
	
	public static RespEntity post(String url, Map<String, Object> headers, Map<String, Object> params) {
		RespEntity entity = new RespEntity("");
		OkHttpClient client = new OkHttpClient();
		FormBody.Builder formBuilder = new FormBody.Builder();
		if (!ValidatorUtil.isEmpty(params)) {
			for (Entry<String, Object> entry : params.entrySet()) {
				formBuilder.add(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
				
			}
		}
		
		FormBody form = formBuilder.build();
		
		Request.Builder requestBuilder = new Request.Builder();
		http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/requestBuilder.addHeader("content-type", "applicationhttp:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/json;charset:UTF-8") ;
		if (!ValidatorUtil.isEmpty(headers)) {
			for (Entry<String, Object> entry : headers.entrySet()) {
				requestBuilder.addHeader(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
			}
		}
		requestBuilder.url(url);
		requestBuilder.post(form);
		Request request = requestBuilder.build();

		Response response = null;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
			entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
			entity.setMsg(e.getMessage());
		}
		if (!response.isSuccessful()) {
			entity.setCode(RespEnums.RESP_OTHER_RESP_CODE.getCode());
			entity.setMsg("error code : "+response.code());
		}
		String result = null;
		try {
			result = response.body().string();
			entity.setData(result);
		} catch (IOException e) {
			e.printStackTrace();
			entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
			entity.setMsg(e.getMessage());
		}
		
		return entity;
	}
	
	
	

	public static void postAsynchronize(String url, Map<String, Object> params) {
		OkHttpClient client = new OkHttpClient();
		Builder builder = new FormBody.Builder();
		for (Entry<String, Object> entry : params.entrySet()) {
			builder.add(entry.getKey(),
					ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
		}
		FormBody form = builder.build();

		Request request = new Request.Builder().url(url).post(form).build();

		Call call = client.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/ 访问失败, 打印访问地址
				Request r = call.request();
				System.out.println("请求失败: " + r.url());
				System.out.println(r.body());
			}

			@Override
			public void onResponse(Call call, Response response)
					throws IOException {
				System.out.println("请求有响应" + call.request().url());
				System.out.println("响应码: " + response.code());
				System.out.println("请求内容: " + response.body().string());
			}
		});
	}

	public static void postSynchronize(String url, Map<String, Object> params) {
		OkHttpClient client = new OkHttpClient();
		Builder builder = new FormBody.Builder();
		for (Entry<String, Object> entry : params.entrySet()) {
			builder.add(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
			
		}
		FormBody form = builder.build();

		Request request = new Request.Builder().url(url).post(form).build();

		Response response = null;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!response.isSuccessful()) {

		}
		String result = null;
		try {
			result = response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	
	public static void uploadFile(String url,File file, Map<String, Object> params) {
		  http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/还是先创建客户端
        OkHttpClient client = new OkHttpClient();
        http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/待上传文件
      http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/  MultipartBody.Part part = MultipartBody.Part .createFormData("upload", file.getName(), RequestBody.create(MultipartBody.FORM, file));
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "lulu")http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/这个参数在服务器端可以接收到
                .addFormDataPart("upload", file.getName(), RequestBody.create(MultipartBody.FORM, file))
                .build();

        Request request = new Request.Builder()
                .url("http:http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/127.0.0.1:8080http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/test")
                .post(multipartBody)
                .build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                System.out.println(response.body().string());
            } else {
                System.out.println("访问失败:" + response.code());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


	}
	
	
}

 

RespEntity .java

 

public class RespEntity implements Serializable{

	 private int code;
	 private String msg;
	 private Object data;
	 private long timestamp ;
	
	 public RespEntity() {  }
	 
	 
	 public RespEntity(Object data ) {
		this.code = RespEnums.RESP_HTTP_SUCCESS.getCode();
		this.msg = RespEnums.RESP_HTTP_SUCCESS.getDesc();
		this.data = data;
		this.timestamp = System.currentTimeMillis();
	 }


	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public Object getData() {
		return this.data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public long getTimestamp() {
		return timestamp;
	}
	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}
}

 

RespEnums .java

public enum RespEnums {
	
	RESP_HTTP_SUCCESS(0,"000","HTTP SUCCESS")
	,RESP_HTTP_ERROR(100,"100","HTTP ERROR")
	
	,RESP_SUCCESS(200,"200","SUCCESS")
	,RESP_VALID_SUCCESS(210,"210","VALID SUCCESS")
	,RESP_VALID_FAIL(211,"211","VALID FAIL")
	,RESP_ERROR(400,"400","ERROR")
	
	,RESP_ERROR_PARAMS_NULL(401,"401","param is null")
	,RESP_ERROR_AUTH_FAIL(402,"402","auth fail")
	,RESP_ERROR_PARAMS_FAIL(403,"403","param fail")
	
	,RESP_OTHER_RESP_CODE(499,"499","OTHER_RESP_CODE")
	,RESP_EXCEPTION(500,"500","EXCEPTION")
	
	
	
	;

	private int code;
    private String sourceCode;
    private String desc;
    
    
    private RespEnums(int code, String sourceCode, String desc){
        this.setCode(code);
        this.setSourceCode(sourceCode);
        this.setDesc(desc);
    }


    http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/**
     * 根据编码获得基础编码对象
     * @param sourceCode
     * @return
     *http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/
    public static RespEnums getBaseBySourceCode(String sourceCode){
    	RespEnums bc = null;
        for(RespEnums baseCodeEnum : RespEnums.values()){
            if (baseCodeEnum.sourceCode.equals(sourceCode)){
                bc = baseCodeEnum;
                break;
            }
        }
        return  bc;
    }

    http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/**
     * 根据编码获得基础编码对象
     * @param code
     * @return
     *http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/
    public static RespEnums getBaseByCode(int code){
    	RespEnums bc = null;
        for(RespEnums baseCodeEnum : RespEnums.values()){
            if (baseCodeEnum.code == code ){
                bc = baseCodeEnum;
                break;
            }
        }
        return  bc;
    }


	public int getCode() {
		return code;
	}


	public void setCode(int code) {
		this.code = code;
	}


	public String getSourceCode() {
		return sourceCode;
	}


	public void setSourceCode(String sourceCode) {
		this.sourceCode = sourceCode;
	}


	public String getDesc() {
		return desc;
	}


	public void setDesc(String desc) {
		this.desc = desc;
	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http:http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/http:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp:http://knight-black-bob.iteye.com/http://knight-black-bob.iteye.com/knight-black-bob.iteye.comhttp://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!


上一条


下一条

相关新闻
自定义表单

本例固定链接: 分享到:
更多