HttpUtil工具類發送post請求

使用apache的HttpClient發送post請求。

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	
	private static String charset = "utf-8";
	
	public static String postMethod(String url, String json) throws ClientProtocolException, IOException{
		HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        
        StringEntity entity = new StringEntity(json, charset);//解決中文亂碼問題    
        entity.setContentEncoding(charset);    
        entity.setContentType("application/json");    
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        
		if(response.getStatusLine().getStatusCode() == 200){
			HttpEntity httpEntity = response.getEntity();
			return EntityUtils.toString(httpEntity, charset);
		}
		return null;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章