美文网首页
java+kotlin+Httplient笔记

java+kotlin+Httplient笔记

作者: 福霜 | 来源:发表于2017-08-02 22:28 被阅读0次

https协议如何通过X509TrustManager接口实现自己创建的证书

java中HttpClient相关请求:


import相关 get请求 post请求 put请求 delete请求

kotlin HttpClient(post)

post请求

利用.apache.commons.httpclient.HttpClient调用接口

导入文件 get/post/put请求

/**

*发起http请求

*

*@paramreqUrl:请求地址

*@parammethod:请求方式

*@paramcharset:编码格式

*@paramparams:map型参数

*@return:字符串

*@throwsIOException

*/

public staticString request(String reqUrl, String method, String charset, Map params) {

if(StringUtils.isBlank(reqUrl) || StringUtils.isBlank(method) ||

StringUtils.isBlank(charset)) {

return null;

}

HttpClient httpClient =newHttpClient();

NameValuePair[] nameValuePair =generateNameValuePair(params);

// GET请求

if(StringUtils.equals("GET", method)) {

GetMethod getMethod =newGetMethod(reqUrl);

getMethod.setQueryString(nameValuePair);

getMethod.getParams().setContentCharset(charset);

try{

httpClient.executeMethod(getMethod);

returnIOUtils.toString(getMethod.getResponseBodyAsStream(), charset);

}catch(IOException e) {

System.out.println(e.getMessage());

}

}

// POST请求

if(StringUtils.equals("POST", method)) {

PostMethod postMethod =newPostMethod(reqUrl);

postMethod.addParameters(nameValuePair);

try{

httpClient.executeMethod(postMethod);

returnIOUtils.toString(postMethod.getResponseBodyAsStream(), charset);

}catch(IOException e) {

System.out.println(e.getMessage());

}

}

// PUT请求

if(StringUtils.equals("PUT", method)) {

PutMethod putMethod =newPutMethod(reqUrl);

putMethod.setQueryString(nameValuePair);

try{

httpClient.executeMethod(putMethod);

returnIOUtils.toString(putMethod.getResponseBodyAsStream(), charset);

}catch(IOException e) {

System.out.println(e.getMessage());

}

}

return null;

}

/**

* MAP类型数组转换成NameValuePair类型

* @param params MAP类型数组

* @return NameValuePair类型数组

*/

private fun generateNameValuePair(params: Map): Array {

val nameValuePair =arrayOfNulls(params.size)

var i =0

    for ((key1, value)in params) {

if (value !=null)

nameValuePair[i++] = NameValuePair(key1, JSON.toJSONString(value))

else

            nameValuePair[i++] = NameValuePair(key1,"")

}

return nameValuePair

}

相关文章

网友评论

      本文标题:java+kotlin+Httplient笔记

      本文链接:https://www.haomeiwen.com/subject/pqpylxtx.html