본문 바로가기

Programming/Java

[Java] HTTP Request with Apache Library

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;


import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.cookie.Cookie;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;


public class HttpHttp {


public static void main(String[] args) {

// TODO Auto-generated method stub


boolean setProxy;

HttpGet httpget;


DefaultHttpClient httpclient = new DefaultHttpClient();


httpget = new HttpGet("http://www.example.com"); // Login주소


try {

// 1. HTTP GET

HttpResponse response = httpclient.execute(httpget);

HttpEntity entity = response.getEntity();

log("getData", EntityUtils.toString(entity));


// 2. HTTP POST

HttpPost httpost = new HttpPost(

"http://posttestserver.com/post.php?dir=../../../cirrus");

// 2-1. setPOST Data

List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("postData1", "datatatata"));

nvps.add(new BasicNameValuePair("status_code", "404"));// 일부러 테스트를

// 위해 404에러가

// 오도록

try {

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

response = httpclient.execute(httpost);

log("POST", response.getStatusLine() + "");

log("POST RETURN", EntityUtils.toString(response.getEntity()));

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


List<Cookie> cookies = httpclient.getCookieStore().getCookies();

if (cookies.isEmpty()) {

log("최초 접근 쿠기", "None");

} else {

for (int i = 0; i < cookies.size(); i++) {

log("최초 접근 쿠기", cookies.get(i).toString());

}

}


} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


private static void log(String tag, String msg) {

System.out.println("[" + tag + "]\t" + msg);


}


public static void dump(String[] entireList) {

for (int i = 0; i < entireList.length; i++) {

System.out.format("array[%d] = %s%n", i, entireList[i]);

}

}


}