package com.httpdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtil {
private static int DEFAULT_TIME_OUT = 5000;// 超时时间 单位毫秒
protected static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
public static String get(String endurls,Map<String,Object> map) throws HttpException, IOException{
return get(endurls,map,null,DEFAULT_TIME_OUT);
}
//拼接url
private static String get(String endurls, Map<String, Object> map,Map<String, Object> headers, int timeOut) throws HttpException, IOException {
String result = null;//返回结果结合
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);//设置超时时间
endurls+="?";
int start=0;
if(map != null){
for (Map.Entry<String, Object> entry:map.entrySet()) {
if(start == 0){
endurls=endurls +entry.getKey() +"="+entry.getValue();
}else{
endurls=endurls +"&"+entry.getKey() +"="+entry.getValue();
}
start++;
}
}
System.out.println(endurls);
//方法处理一
String xmlresult=result( endurls);
//方法处理2
return xmlresult;
}
//对网络地址进行处理
private static String result (String endurls) throws IOException {
URL getUrl = new URL(endurls);
HttpURLConnection connection =(HttpURLConnection)getUrl.openConnection();
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line="";
while ((line=reader.readLine())!= null) {
sb.append(line);
}
reader.close();
connection.disconnect();
return sb.toString();
}
private static String result(String endurls,Map<String, Object> headers, HttpClient httpClient,String result) throws HttpException, IOException{
HttpMethod httpMethod =new GetMethod(endurls);
if(null != headers){ //
for (Map.Entry<String, Object> entry:headers.entrySet()) {
httpMethod.addRequestHeader(entry.getKey(), entry.getValue().toString());
}
}
//发送请求
int statusCode = httpClient.executeMethod(httpMethod);
// 请求状态不等200时不成功
if(statusCode != HttpStatus.SC_OK){
logger.error("网络连接异常,GET请求失败,请求地址:"+ endurls + "返回状态码:"+ statusCode);
throw new HttpException("网络连接异常");
}
InputStream inputStream = httpMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String string = "";
StringBuffer stringBuffer = new StringBuffer();
while ((string=br.readLine())!= null) {
stringBuffer.append(string);
}
inputStream.close(); //关流
httpMethod.releaseConnection();//释放连接
httpClient.getHttpConnectionManager().closeIdleConnections(0);
result=stringBuffer.toString();
return result;
}
public static String delete(String endurls, Map<String,Object> map,Map<String,String> headers,int timeOut) throws IOException, IOException{
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build();
if(map != null){
List<NameValuePair> nvps =new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry:map.entrySet()) {
if(entry.getValue() != null && !"".equals(entry.getValue())){
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
if(!nvps.isEmpty()){
endurls += "?" +URLEncodedUtils.format(nvps, "utf-8");
}
}
}
HttpRequestBase request = new HttpDelete(endurls);
request.setConfig(requestConfig);
if(headers != null){
Iterator<String> it = headers.keySet().iterator();
while(it.hasNext()){
String key = it.next();
String value = headers.get(key);
request.addHeader(key, value);
}
}
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
return EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
return "";
}
public static void main(String[] args) {
String url="http://www.tuling123.com/openapi/api?key=b9c73434132c08a17a70eb977d743f3b&info=讲个故事";
String endurls="http://www.tuling123.com/openapi/api";
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", "b9c73434132c08a17a70eb977d743f3b");
map.put("info", "你叫什么名字");
try {
String result = HttpClientUtil.get(endurls, map);
System.out.println(result);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
聊天机器人_远程接口javautil
最新推荐文章于 2022-03-06 21:33:48 发布