利用okhttp,通过http协议请求。写下此笔记,记录常用的请求方法,如get,post请求方法,以及表单提交,文件上传,xml请求soap协议的webservice等等,具体详细用法参考http://www.tuicool.com/articles/3INNz2
package com.gosun.core.httpreq;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import com.gosun.core.json.JsonUtil;
import com.gosun.core.utils.DCCWSReqClient;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import net.sf.json.JSONObject;
/**
* http请求
* @author liuxg
* @date 2016年2月19日 上午11:27:01
*/
public class OkHttpReqDemo {
public static void main(String[] args) {
/*try {
//new OkHttpReqDemo().get();
//new OkHttpReqDemo().formPost();
//new OkHttpReqDemo().xmlPost();
//new OkHttpReqDemo().uploadFile();
//new OkHttpReqDemo().fileUpload();
} catch (IOException e) {
e.printStackTrace();
}*/
}
/**
* get请求
* @throws IOException
*/
public void get() throws IOException {
String url = "http://localhost:8080/gircs/metadata/batchImport/testGet?name=123&password=234";
HttpReqUtil.get(url);
}
/**
* post请求
* @throws IOException
*/
public void formPost() throws IOException {
RequestBody body = new FormEncodingBuilder()
.add("name", "name")
.add("password", "password")
.build(); HttpReqUtil.post("http://localhost:8080/gircs/metadata/batchImport/testFormPost", body);
}
/**
* xml请求关键在于设置请求头部mediaType
* @throws IOException
*/
public void xmlPost() throws IOException{
String url = "http://192.168.27.218:8085/dataSourceWebService?wsdl";
JSONObject params = JsonUtil.getInstance().putData("node_id", 147).putData("page", 1).putData("limit", 5)
.getJo();
RequestBody body = RequestBody.create(MediaType.parse("text/xml;charset=UTF-8"), getSoapRequestData("getDbMetaDatas",params));
Response response = HttpReqUtil.post(url, body);
System.out.println(response.body().string());
}
/**
* 文件上传,模拟表单的提交
* @throws IOException
*/
public void fileUpload() throws IOException{
//没有指定上次file的name是什么,后台直接在request的请求中获取输入流,转化成文件,不能用multipart接受
RequestBody fileBody = RequestBody
.create(MediaType.parse("image/png"), new File("E:\\color.png"));
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("name", "name")
.addFormDataPart("password", "password")
.addFormDataPart("file", "liuxg", fileBody)
.build();
HttpReqUtil.post("http://localhost:8080/gircs/metadata/batchImport/testUploadFile", body);
}
/**
* 凑成xml格式字符串
* @param methodName
* @param params
* @return
*/
@SuppressWarnings("rawtypes")
private String getSoapRequestData(String methodName, JSONObject params) {
StringBuffer sb = new StringBuffer(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.datasource.gosun.com/\">");
sb.append("<soapenv:Header/><soapenv:Body>");
sb.append("<web:" + methodName + ">");
Iterator it = params.keys();
while (it.hasNext()) {
String key = (String) it.next();
String value = params.getString(key);
sb.append("<" + key + ">" + value + "</" + key + ">");
}
sb.append("</web:" + methodName + ">");
sb.append("</soapenv:Body></soapenv:Envelope>");
return sb.toString();
}
}
package com.gosun.core.httpreq;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.gosun.core.utils.Constants;
import com.gosun.service.entity.UserRsp;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
/**
* http请求工具类,注意理解http请求中header的作用
* @author liuxg
* @date 2016年2月19日 上午11:27:12
*/
public class HttpReqUtil {
/**
* get方式请求
* @param url
* @return 服务器返回值
* @throws IOException
*/
public static Response get(String url) throws IOException {
Request request = new Request.Builder().url(url)
.build();
Response response = new OkHttpClient().newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("请求有错:" + response);
return response;
}
/**
* post方式请求
*
* @param url
* @param params
* 参数,已json方式传参
* @return 服务器返回值
* @throws IOException
*/
public static Response post(String url, RequestBody body) throws IOException {
Request request = new Request.Builder().url(url)
.post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("请求有错:" + response);
return response;
}
}