[Java] HttpClient發送http get/post request

下載並加入HttpClient jar

https://hc.apache.org/downloads.cgi

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
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.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpRequester {

	public CloseableHttpResponse sendPost(String url, List paras, HashMap headers, UsernamePasswordCredentials creds,  String encoding) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost post = new HttpPost(url);
			if(paras!=null) {
				post.setEntity(new UrlEncodedFormEntity(paras));
			}
			if(headers!=null) {
				if(headers.size()>0) {
					for(Map.Entry h:headers.entrySet()){    
						post.setHeader(h.getKey(), h.getValue());  
					}  
				}
			}
			if(creds!=null) {
				post.addHeader(new BasicScheme().authenticate(creds, post, null));
			}
			CloseableHttpResponse res = client.execute(post);
			int statusCode = res.getStatusLine().getStatusCode();
			System.out.println("Status code: " + statusCode);
			if(statusCode>=200 && statusCode<300) {
				return res;
			}else {
				throw new ClientProtocolException("Unexpected response status: " + statusCode);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			client.close();
		}
		return null;
	}
	
	public CloseableHttpResponse sendGet(String url) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
	    HttpGet httpget = new HttpGet(url);
	    CloseableHttpResponse rs = httpclient.execute(httpget);
	    if(rs.getStatusLine().getStatusCode()==200){
	      return rs;
	    }
	    return null;
	  }
	
	public String resToContent(CloseableHttpResponse res) {
		try {
			InputStream is = res.getEntity().getContent();
			if(is!=null) {
				BufferedReader bufferedReader = new BufferedReader(
	                    new InputStreamReader(is));
				String str;
		        StringBuffer temp = new StringBuffer();
		        while((str = bufferedReader.readLine())!=null){
		          temp.append(str);
		        }
		        return temp.toString();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

調用

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpRequester hr = new HttpRequester();
		CloseableHttpResponse resGet = hr.sendGet("https://google.com");
		List paras = new ArrayList();
		HashMap headers = new HashMap();
		headers.put("Accept", "application/json");
		paras.add(new BasicNameValuePair("", ""));
		UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", "");
		CloseableHttpResponse resPost = hr.sendPost("http://localhost", paras, headers, creds, "utf-8");
		//papas, heanders, creds can be null
		String contentGet = hr.resToContent(resGet);
		String contentPost = hr.resToContent(resPost);
		System.out.println(contentGet);
		System.out.println(contentPost);
  }