Java傳送HTTP的get,post請求(JSON)
阿新 • • 發佈:2018-12-18
Java傳送HTTP的get,post請求(JSON)
import net.sf.json.JSONObject; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.IOException; /** * Created by liqun.chen on 2017/5/15. */ public class HttpUtil { /** * json 字串 * @param url * @param param * @return */ public static String getSerchPersion(String url,String param){ /* 1 生成 HttpClinet 物件並設定引數 */ HttpClient httpClient = new HttpClient(); // 設定 Http 連線超時為5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 物件並設定引數 */ GetMethod getMethod = new GetMethod(url); // 設定 get 請求超時為 5 秒 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); // 設定請求重試處理,用的是預設的重試處理:請求三次 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); String response = ""; /* 3 執行 HTTP GET 請求 */ try { int statusCode = httpClient.executeMethod(getMethod); /* 4 判斷訪問的狀態碼 */ if (statusCode != HttpStatus.SC_OK) { System.err.println("請求出錯: "+ getMethod.getStatusLine()); } /* 5 處理 HTTP 響應內容 */ // HTTP響應頭部資訊,這裡簡單列印 Header[] headers = getMethod.getResponseHeaders(); for (Header h : headers) System.out.println(h.getName() + "------------ " + h.getValue()); // 讀取 HTTP 響應內容,這裡簡單列印網頁內容 byte[] responseBody = getMethod.getResponseBody();// 讀取為位元組陣列 response = new String(responseBody, param); System.out.println("----------response:" + response); // 讀取為 InputStream,在網頁內容資料量大時候推薦使用 // InputStream response = getMethod.getResponseBodyAsStream(); } catch (HttpException e) { // 發生致命的異常,可能是協議不對或者返回的內容有問題 System.out.println("請檢查輸入的URL!"); e.printStackTrace(); } catch (IOException e) { // 發生網路異常 System.out.println("發生網路異常!"); e.printStackTrace(); } finally { /* 6 .釋放連線 */ getMethod.releaseConnection(); } return response; } /** * post請求 * @param url * @param json * @return */ public static JSONObject doPost(String url,JSONObject json){ DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//傳送json資料需要設定contentType post.setEntity(s); HttpResponse res = client.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity entity = res.getEntity(); String result = EntityUtils.toString(res.getEntity());// 返回json格式: response = JSONObject.fromObject(result); } } catch (Exception e) { throw new RuntimeException(e); } return response; }
//呼叫 public static void main(String arg[]) throws Exception { String url = "http://localhost:8080/"; JSONObject params = new JSONObject(); params.put("personName", "name"); params.put("personCode", "230882xxxxxx2116"); JSONObject param2 = new JSONObject(); param2.put("pageNo", 1); param2.put("pageSize", 20); params.put("page", param2); String param = "q="+params.toString(); //get 請求 String ret = getSerchPersion(url, param.toString()); System.out.println(ret); // JSONObject jsonResponse=JSONObject.fromObject(param); // JSONObject json = (JSONObject)jsonResponse.get("page"); // System.out.println(json.get("pageSize")); //post 請求 JSONObject jsonObject = doPost(url,params); System.out.println(jsonObject.toString()); }