Java中的httpclient4.5应该怎么使用? Java中的httpclient4.5应该怎么使用

Java\u4e2d\u7684httpclient4.5\u5e94\u8be5\u600e\u4e48\u4f7f\u7528

\u4e00\u3001\u6240\u9700\u8981\u7684jar\u5305
httpclient-4.5.jar
httpcore-4.4.1.jar
httpmime-4.5.jar
\u4e8c\u3001\u5b9e\u4f8b
Java\u4ee3\u7801
package cn.tzz.apache.httpclient;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpClientUtil {
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build();

private static HttpClientUtil instance = null;
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
if (instance == null) {
instance = new HttpClientUtil();
}
return instance;
}

/**
* \u53d1\u9001 post\u8bf7\u6c42
* @param httpUrl \u5730\u5740
*/
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// \u521b\u5efahttpPost
return sendHttpPost(httpPost);
}

/**
* \u53d1\u9001 post\u8bf7\u6c42
* @param httpUrl \u5730\u5740
* @param params \u53c2\u6570(\u683c\u5f0f:key1=value1&key2=value2)
*/
public String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// \u521b\u5efahttpPost
try {
//\u8bbe\u7f6e\u53c2\u6570
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}

/**
* \u53d1\u9001 post\u8bf7\u6c42
* @param httpUrl \u5730\u5740
* @param maps \u53c2\u6570
*/
public String sendHttpPost(String httpUrl, Map maps) {
HttpPost httpPost = new HttpPost(httpUrl);// \u521b\u5efahttpPost
// \u521b\u5efa\u53c2\u6570\u961f\u5217
List nameValuePairs = new ArrayList();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}


/**
* \u53d1\u9001 post\u8bf7\u6c42\uff08\u5e26\u6587\u4ef6\uff09
* @param httpUrl \u5730\u5740
* @param maps \u53c2\u6570
* @param fileLists \u9644\u4ef6
*/
public String sendHttpPost(String httpUrl, Map maps, List fileLists) {
HttpPost httpPost = new HttpPost(httpUrl);// \u521b\u5efahttpPost
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
for (String key : maps.keySet()) {
meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
}
for(File file : fileLists) {
FileBody fileBody = new FileBody(file);
meBuilder.addPart("files", fileBody);
}
HttpEntity reqEntity = meBuilder.build();
httpPost.setEntity(reqEntity);
return sendHttpPost(httpPost);
}

/**
* \u53d1\u9001Post\u8bf7\u6c42
* @param httpPost
* @return
*/
private String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// \u521b\u5efa\u9ed8\u8ba4\u7684httpClient\u5b9e\u4f8b.
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
// \u6267\u884c\u8bf7\u6c42
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// \u5173\u95ed\u8fde\u63a5,\u91ca\u653e\u8d44\u6e90
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}

/**
* \u53d1\u9001 get\u8bf7\u6c42
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// \u521b\u5efaget\u8bf7\u6c42
return sendHttpGet(httpGet);
}

/**
* \u53d1\u9001 get\u8bf7\u6c42Https
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// \u521b\u5efaget\u8bf7\u6c42
return sendHttpsGet(httpGet);
}

/**
* \u53d1\u9001Get\u8bf7\u6c42
* @param httpPost
* @return
*/
private String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// \u521b\u5efa\u9ed8\u8ba4\u7684httpClient\u5b9e\u4f8b.
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
// \u6267\u884c\u8bf7\u6c42
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// \u5173\u95ed\u8fde\u63a5,\u91ca\u653e\u8d44\u6e90
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}

/**
* \u53d1\u9001Get\u8bf7\u6c42Https
* @param httpPost
* @return
*/
private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// \u521b\u5efa\u9ed8\u8ba4\u7684httpClient\u5b9e\u4f8b.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);
// \u6267\u884c\u8bf7\u6c42
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// \u5173\u95ed\u8fde\u63a5,\u91ca\u653e\u8d44\u6e90
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
}

public static String sendGetRequest(String url,String encode){System.out.println("url:=====>>>>>>"+ url);HttpClient httpclient = null;GetMethod get = null;StringBuffer result = new StringBuffer(""); BufferedReader in = null; try {httpclient = new HttpClient();get = new GetMethod(url);get.setRequestHeader("Content-Type","text/xml"); get.setRequestHeader("charset",encode); int statuCode = httpclient.executeMethod(get); if(statuCode==HttpStatus.SC_OK){ //\u8bf7\u6c42\u6210\u529f\uff0c\u8fd4\u56de200 in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),encode)); //\u5c06\u8fd4\u56de\u7684\u6570\u636e\u8bfb\u5165IO\u6d41 String line; while((line=in.readLine())!=null){ result.append(line); } } } catch (Exception e) {e.printStackTrace();}finally{ try { if(in!=null){ in.close(); } if(get!=null){ get.releaseConnection(); }} catch (IOException e) {e.printStackTrace();}} System.out.println("result====>>>"+result);return result.toString();}\u6211\u7528\u7684\u7248\u672c\u662f3.1\u7684\uff0c4.5\u6ca1\u7528\u8fc7\uff0c\u4e0d\u8fc7\u5927\u540c\u5c0f\u5f02\u5427\u3002\u8fd9\u91cc\u6211\u5c01\u88c5\u4e86\u4e00\u4e2a\u65b9\u6cd5\uff0c\u4f60\u53c2\u8003\u4e00\u4e0b\u3002\u4ee5get\u65b9\u5f0f\u8bf7\u6c42url\u662f\u8bf7\u6c42\u5730\u5740\uff0cencode\u662f\u8bf7\u6c42\u7f16\u7801\uff0c\u8bbe\u4e3autf-8\u5c31\u884c\uff0c\u8fd4\u56de\u503c\u662f\u8bf7\u6c42\u5230\u7684\u5185\u5bb9\u3002
\u9644\u4ef6\u4e2d\u662f\u6e90\u4ee3\u7801\uff0c\u611f\u5174\u8da3\u53ef\u4ee5\u770b\u4e00\u4e0b\u3002

  1. package org.apache.http.examples.client;
    import java.net.URI;
    import java.util.List;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.client.methods.RequestBuilder;
    import org.apache.http.cookie.Cookie;
    import org.apache.http.impl.client.BasicCookieStore;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;

    /**
    * A example that demonstrates how HttpClient APIs can be used to perform
    * form-based logon.
    */

  2. public class ClientFormLogin { public static void main(String[] args) throws Exception {       BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCookieStore(cookieStore)
    .build();
    try {

  3. HttpGet httpget = new HttpGet("https://someportal/");
    CloseableHttpResponse response1 = httpclient.execute(httpget);
    try {HttpEntity entity = response1.getEntity();
    System.out.println("Login form get: " + response1.getStatusLine());
    EntityUtils.consume(entity);
    System.out.println("Initial set of cookies:");

  4. List<Cookie> cookies = cookieStore.getCookies();
    if (cookies.isEmpty()) {System.out.println("None");} else {for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); }}           } finally {response1.close();}

  5. HttpUriRequest login = RequestBuilder.post()
    .setUri(new URI("https://someportal/"))
    .addParameter("IDToken1", "username")
    addParameter("IDToken2", "password")
    .build();CloseableHttpResponse response2 = httpclient.execute(login);

  6. try {HttpEntity entity = response2.getEntity();

    System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity);

    System.out.println("Post logon cookies:")

    List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size();

    i++) {}finally { response2.close();

  7. finally}



Java中的httpclient4.5使用:

HttpClient client = new HttpClient();
GetMethod get = new GetMethod(Url);
client.executeMethod(get);
if (get.getStatusCode() != HttpStatus.SC_OK) {
System.out.println("无返回或返回不正确");
}
String repMsg = get.getResponseBodyAsString();



扩展阅读:x86国产cpu ... java windowbuilder ... java.52emu.cn ... javascript高级视频 ... javascript免费网站 ... java官网官网 ... 任天堂网站入口 ... javascript 在线 ... linux网站入口 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网