HttpClient調用http接口(POST)


調用方法,傳過去接口地址和參數(json對象或者map,在方法里轉成json字符串)

JSONObject.toJSONString(map)

JSONObj.toString()

 

 

public static String getResult(String url,Map<String, String> params){
        String returnValue = null;
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
        try {
             HttpPost httppost = new HttpPost(url);
             httppost.addHeader("Content-type","application/json; charset=utf-8");  
             httppost.setHeader("Accept", "application/json");
            
             StringEntity entity = new StringEntity(JSONObject.toJSONString(params),Charset.forName("UTF-8"));    
             httppost.setEntity(entity);
             
             HttpResponse resp = httpclient.execute(httppost);
             if(resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                String   respContent = EntityUtils.toString(he,"UTF-8");
                returnValue =  respContent;
             }
        }
        catch (SocketTimeoutException e) {
             e.printStackTrace();
             returnValue = "timeout";
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
           // 關閉連接,釋放資源
            httpclient.getConnectionManager().shutdown();
       }
       return  returnValue;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM