post json 제출

2480 단어 json
package post;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.http.Header;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class PostHttp {

private static final String APPLICATION_JSON = "application/json";
    
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		DefaultHttpClient httpClient = new DefaultHttpClient();
		String url = "http://localhost:8080/test/dischoose/save.jspx";
		HttpPost httpPost = new HttpPost(url);
		 httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		String encoderJson = "jsonString";
		   encoderJson = URLEncoder.encode(encoderJson, HTTP.UTF_8);
		StringEntity se = new StringEntity(encoderJson);
		 se.setContentType(CONTENT_TYPE_TEXT_JSON);
		  se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		  httpPost.setEntity(se);
	                                                 //       
		  HttpResponse response = httpClient.execute(httpPost);
		  HttpEntity   entity = response.getEntity();            
		try {
			System.out.println("----------------------------------------");
			System.out.println(response.getStatusLine()); //        
			Header[] headers = response.getAllHeaders(); //    HTTP   
			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			System.out.println("----------------------------------------");
			String responseString = null;
			if (response.getEntity() != null) {
				responseString = EntityUtils.toString(response.getEntity()); //         HTML  
				System.out.println(responseString); //          HTML  
			}
		} finally {
			if (entity != null)
				entity.consumeContent(); // release connection gracefully
		}
		return;
	}

}

좋은 웹페이지 즐겨찾기