使用httpclient 連線 restful webservices例項 絕對可用 get的--post

瓜瓜東西發表於2014-10-21
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;

	}

}




相關文章