httpClient使用

測試類請求,post方式html

 1     public static void main(String[] args) throws HttpException, IOException {
 2         Map<String, String> content=new HashMap<String, String>();
 3         content.put("bankName", "浦發銀行");
 4         content.put("cardCode", "62109810*****91");
 5         content.put("customerName", "董*");
 6         content.put("idCode", "152323199****271X");
 7         content.put("telephone", "157273073**");
 8         Map<String, Object> map=new HashMap<String, Object>();
 9         map.put("contractname", "contractAuthorization");
10         map.put("messages",content);
11         PostMethod method = new PostMethod("http://ip:8080/hexin-contract/contract/create");
12         method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
13         method.setParameter("messages",JSON.toJSONString(content));
14         method.setParameter("contractname", "contractAuthorization");
15         HttpClient httpClient = new HttpClient();
16         int statusCode = httpClient.executeMethod(method);
17         if (statusCode == HttpStatus.SC_OK) {
18             //返回附件
19             Header[] headers = method.getResponseHeaders();
20             OutputStream os=new FileOutputStream("C:\\Users\\Administrator\\Desktop\\aa.pdf");
21             for (Header h : headers)
22                 System.out.println(h.getName() + "------------ " + h.getValue());
23             byte[] responseBody = method.getResponseBody();// 讀取爲字節數組
24             os.write(responseBody, 0, responseBody.length);
25             //返回string
26 //            String response = new String(responseBody, "UTF-8");
27 //            System.out.println("response:" + response);
28         }
29     }
30     

頁面解析,連接轉爲流數組

get方式post

URL url = new URL(htmlUrl);
InputStream openStream = url.openStream();

post方式測試

PostMethod method = new PostMethod(htmlUrl);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        method.setParameter("contractName", contractName);
        method.setParameter("content", content);
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(method);
        InputStream openStream=null;
        if (statusCode == HttpStatus.SC_OK) {
            openStream=new ByteArrayInputStream(method.getResponseBody()); 
        }
相關文章
相關標籤/搜索