使用httpclient 串連 restful webservices執行個體 絕對可用 get的--post__web

來源:互聯網
上載者:User
package org.glassfish.jersey.examples.httpclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient; public class ApacheHttpClientGet {     public static void main(String[] args) {      try {         DefaultHttpClient httpClient = new DefaultHttpClient();        HttpGet getRequest = new HttpGet(//            "http://localhost:8080/RESTfulExample/json/product/get");    "http://10.16.232.79:8555/base/helloworld/h");//        getRequest.addHeader("accept", "application/json");        getRequest.addHeader("accept", "text/plain");         HttpResponse response = httpClient.execute(getRequest);         if (response.getStatusLine().getStatusCode() != 200) {            throw new RuntimeException("Failed : HTTP error code : "               + response.getStatusLine().getStatusCode());        }         BufferedReader br = new BufferedReader(                         new InputStreamReader((response.getEntity().getContent())));         String output;        System.out.println("Output from Server .... \n");        while ((output = br.readLine()) != null) {            System.out.println(output);        }        httpClient.getConnectionManager().shutdown();       } catch (ClientProtocolException e) {         e.printStackTrace();       } catch (IOException e) {         e.printStackTrace();      }     } }


post:
<pre name="code" class="html">package org.glassfish.jersey.examples.httpclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URI;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicHeader;import org.apache.http.protocol.HTTP;public class ApacheHttpClientPost {public static void main(String[] args) {ApacheHttpClientPost post = new ApacheHttpClientPost();try {//post.doPost("http://localhost:8080/RESTfulExample/json/product/post", "{\"qty\":100,\"name\":\"iPad 4\"}");//post.doPost("http://1sss:8555/base/helloworld/post", "{\"qty\":100,\"name\":\"iPad 4\"}");post.doPost("http://abc/def", "{\"sort\":100,\"name\":\"iPad 4\"}");} catch (Exception e) {e.printStackTrace();}/*try {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost postRequest = new HttpPost("http://10.16.232.79:8555/base/helloworld/post");StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");input.setContentType("application/json");postRequest.setEntity(input);HttpResponse response = httpClient.execute(postRequest);if (response.getStatusLine().getStatusCode() != 201) {throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());}BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));String output;System.out.println("Output from Server .... \n");while ((output = br.readLine()) != null) {System.out.println(output);}httpClient.getConnectionManager().shutdown();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}*/}// public String doPost(String wcfUrl,JSONObject jsonObject) throws// Exception {public String doPost(String wcfUrl, String jsonObject) throws Exception {HttpClient httpClient = new DefaultHttpClient();HttpResponse response;HttpPost post = new HttpPost();HttpEntity httpEntity;StringEntity stringEntity = new StringEntity(jsonObject.toString());stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));httpEntity = stringEntity;post.setEntity(httpEntity);post.setURI(new URI(wcfUrl));post.setHeader("Content-type", "application/json");response = httpClient.execute(post);return parseHttpResponse(response);}public String parseHttpResponse(HttpResponse response) throws Exception {String jsonString = "";int status = response.getStatusLine().getStatusCode();if (status == 200) {BufferedReader bReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = bReader.readLine()) != null) {sb.append(line + NL);}jsonString = sb.toString();bReader.close();}return jsonString;}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.