HttpUtil tool class:
package com.qq.util; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpUtil { // Create HttpClient object public static HttpClient httpClient = new DefaultHttpClient(); public static final String BASE_URL = "http://180.201.156.166:8080/trial/"; /** * * @param url the URL to send the request to * @return server response string * @throws Exception */ public static String getRequest(final String url) throws Exception { FutureTask<String> task = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { // Create the HttpGet object. HttpGet get = new HttpGet(url); // send GET request HttpResponse httpResponse = httpClient.execute(get); // if the server returns a response successfully if (httpResponse.getStatusLine() .getStatusCode() == 200) { // Get the server response string String result = EntityUtils .toString(httpResponse.getEntity()); return result; } return null; } }); new Thread(task).start(); return task.get(); } /** * @param url the URL to send the request to * @param params request parameters * @return server response string * @throws Exception */ public static String postRequest(final String url , final Map<String ,String> rawParams)throws Exception { FutureTask<String> task = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { // Create the HttpPost object. HttpPost post = new HttpPost(url); // If the number of passed parameters is relatively large, the passed parameters can be encapsulated List<NameValuePair> params = new ArrayList<>(); for(String key : rawParams.keySet()) { // encapsulate request parameters params.add(new BasicNameValuePair(key , rawParams.get(key))); } // set request parameters post.setEntity(new UrlEncodedFormEntity( params, "gbk")); // send POST request HttpResponse httpResponse = httpClient.execute(post); // if the server returns a response successfully if (httpResponse.getStatusLine() .getStatusCode() == 200) { // Get the server response string String result = EntityUtils .toString(httpResponse.getEntity()); return result; } return null; } }); new Thread(task).start(); return task.get(); } }
Call method:
String url ="http://192.168.191.1:8080/trial/LoginServlet"; String string = HttpUtil.getRequest(url);