Http post方式發送json資料

來源:互聯網
上載者:User

標籤:android   json   http   post   

HttpClient類比get,post請求並發送請求參數(json等)
import java.io.IOException;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpStatus;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;/** *  */public class HttpClientUtil {  public static void main(String arg[]) throws Exception {    String url = "test.com";    JSONObject params = new JSONObject();    params.put("SRC_STM_CODE", "wsf");    params.put("TENANT_ID", "123");    params.put("NM", "張三");    params.put("BRTH_DT", "1983-01-20");    params.put("GND_CODE", "1");    JSONArray params2 = new JSONArray();    JSONObject param3 = new JSONObject();    param3.put("DOC_TP_CODE", "10100");    param3.put("DOC_NBR", "100200198301202210");    param3.put("DOC_CUST_NM", "test");    params2.add(param3);    params.put("DOCS", params2);    String ret = doPost(url, params).toString();    System.out.println(ret);  }  /**   httpClient的get請求方式2   * @return   * @throws Exception   */  public static String doGet(String url, String charset)      throws Exception {    /*     * 使用 GetMethod 來訪問一個 URL 對應的網頁,實現步驟: 1:產生一個 HttpClinet 對象並設定相應的參數。     * 2:產生一個 GetMethod 對象並設定響應的參數。 3:用 HttpClinet 產生的對象來執行 GetMethod 產生的Get     * 方法。 4:處理響應狀態代碼。 5:若響應正常,處理 HTTP 響應內容。 6:釋放串連。     */    /* 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, charset);      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;  }}

Http post方式發送json資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.