2010. 7. 6. 10:10

안드로이드 http connection UTF-->euc-kr




 
package com.qnsolv.vanmsm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Hashtable;

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.HttpClient;
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.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import com.qnsolv.vanmsm.common.SI;


/*
 * HttpUtil client = new HttpUtil(LOGIN_URL);  
client.AddParam("accountType", "GOOGLE");  
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {  
    client.Execute(RequestMethod.POST);
} catch (Exception e) {  
    e.printStackTrace(); 
}  
String response = client.getResponse();
 */
public class HttpUtil {
	private String defaultUrl="";//자신의 서버url
	private ArrayList params;
	private ArrayList headers;
	private String url;
	private int responseCode;
	private String message;
	private String response;
	public String METHOD_GET = "GET";
	public String METHOD_POST = "POST";
	public int networkTime=20000;
	public Hashtable getResponse() {
		return VanUtil.packetAnalyis(response);
	}
	public String getErrorMessage() {
		return message;
	}
	public int getResponseCode() {
		return responseCode;
	}

	public HttpUtil(String url)
	{
		this.url = defaultUrl+url;
		params = new ArrayList();
		headers = new ArrayList();
	}

	public void AddParam(String name, String value)
	{
		params.add(new BasicNameValuePair(name, value));
	}

	public void AddHeader(String name, String value)
	{
		headers.add(new BasicNameValuePair(name, value));
	}
	
	public void execute(String method) throws Exception
	{
		if (method.equals(METHOD_GET)) {
			String combinedParams = "";
			if (!params.isEmpty()) {
				combinedParams += "?";
				for (NameValuePair p : params)
				{
					String urlEncoderStr="";
					try {
						urlEncoderStr = URLEncoder.encode(p.getValue(),"euc-kr");
					} catch (Exception e) {
						// TODO: handle exception
					}
					String paramString = p.getName() + "=" + urlEncoderStr;
					if (combinedParams.length() > 1)
					{
						combinedParams += "&" + paramString;
					}
					else
					{
						combinedParams += paramString;
					}
				}
			}
			VanUtil.println("DEBUG",this.getClass().getName() + " :="+url + combinedParams);
			HttpGet requestGet = new HttpGet(url + combinedParams);
			// add headers
			requestGet.addHeader("Accept", "text/plain, text/html, text/*");
			requestGet.addHeader("Referer", "vw.qnsolv.com");
			requestGet.addHeader("Host", "vw.qnsolv.com:8080");
			requestGet.addHeader("Connection", "Keep-Alive");
			requestGet.addHeader("User-Agent", "");
			requestGet.addHeader("Content-Type", "text/html;charset=UTF8");
			executeRequest(requestGet, url);
		} else if (method.equals(METHOD_POST)) {
			HttpPost request = new HttpPost(url);

			request.addHeader("Accept", "text/plain, text/html, text");
			if (!params.isEmpty()) {
				request.setEntity(new UrlEncodedFormEntity(params, HTTP.ISO_8859_1));
			}
			executeRequest(request, url);
		}

	}

	private void executeRequest(HttpUriRequest request, String url)
	{

		HttpParams httpParameters = new BasicHttpParams();  
		int timeoutConnection = networkTime; 
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
		int timeoutSocket = networkTime; 
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
		
		
		HttpClient client = new DefaultHttpClient(httpParameters);

	 

		HttpResponse httpResponse;
		try {
			
			httpResponse = client.execute(request);
			responseCode = httpResponse.getStatusLine().getStatusCode();
			message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {

				InputStream instream = entity.getContent();
				response = convertStreamToString(instream);
				Hashtable ht = VanUtil.packetAnalyis(response);
				// Closing the input stream will trigger connection release
				instream.close();
			}

		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
			response=SI.gI().getVanDefaultCode()+"00000100W99네트워크 연결 지연 \n( 네트워트 연결시간 "+(networkTime/1000)+" 초)   ";
		} catch (IOException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
			response=SI.gI().getVanDefaultCode()+"00000100W99네트워크 연결 지연 \n( 네트워트 연결시간 "+(networkTime/1000)+" 초)    ";
		}
	}

	private static String convertStreamToString(InputStream is) {

		StringBuilder sb = new StringBuilder();
		
		try{
			BufferedReader reader= new BufferedReader(new InputStreamReader(is,"EUC-KR"));
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			
		}
		
		
		return sb.toString();

	}

}