天天看點

httpclient get/post請求

public static String httpPost(String url, JSONObject json) {

String respContent = null;

try{

HttpPost httpPost = new HttpPost(url);

CloseableHttpClient client = HttpClients.createDefault();

// json方式

StringEntity entity = new StringEntity(json.toString(), "utf-8");// 解決中文亂碼問題

entity.setContentEncoding("UTF-8");

entity.setContentType("application/json");

httpPost.setEntity(entity);

System.out.println();

HttpResponse resp = client.execute(httpPost);

if (resp.getStatusLine().getStatusCode() == 200) {

HttpEntity he = resp.getEntity();

respContent = EntityUtils.toString(he, "UTF-8");

}

}catch (Exception ex) {

// TODO: handle exception

respContent=null;

}finally {

return respContent;

/**

* @param url

* 要請求的位址

* @return 狀态碼

* @throws IOException

* @throws ClientProtocolException

*/

public static String httpGet(String url) {

String urlNameString = url;

String status = null;

try {

// 根據位址擷取請求

HttpGet request = new HttpGet(urlNameString);// 這裡發送get請求

request.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,3000 );

// 擷取目前用戶端對象

HttpClient httpClient = new DefaultHttpClient();

// 通過請求對象擷取響應對象

HttpResponse response;

response = httpClient.execute(request);

// 判斷網絡連接配接狀态碼是否正常(0--200都數正常)

if (response.getStatusLine().getStatusCode() == 200) {

status = "200";

catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

log.error(e);

finally {

return status;