[JAVA] 實作 Http Request 功能.

用JAVA 實作 Http request的功能.

附上程式碼Sample.

package HtteRequestSample;

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
  
import java.io.OutputStream;  
  
import java.net.HttpURLConnection;  
import java.net.MalformedURLException;  
  
import java.net.URL;

import org.json.JSONArray;
public class HttpUtil {

	public String httpRequest(String method,String targetUrl,String requestBodyJson) throws ClassTypeException {
		HttpURLConnection connection = null;
		StringBuffer sb = new StringBuffer("");
		
		try {
			URL url = new URL(targetUrl);
			connection = (HttpURLConnection) url.openConnection();

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);// POST,GET,POST,DELETE,INPUT
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);

			//connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//connection.setRequestProperty("Content-Type", "text/xml");  
			connection.setRequestProperty("Accept", "application/json");
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			//connection.setRequestProperty("charset", "UTF-8");
			connection.connect();

			OutputStream out = connection.getOutputStream();
			out.write(requestBodyJson.getBytes());
			out.flush();
			out.close();
  
			BufferedReader reader = new BufferedReader(new InputStreamReader(
			connection.getInputStream(),"UTF-8"));
			
			String lines="";
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append( lines);
			}
			System.out.println(sb);
			reader.close();
			connection.disconnect();
		} catch (MalformedURLException e) {  
			throw e;
		} catch (UnsupportedEncodingException e) {
			throw e;
		} catch (IOException e) {
			throw e;  
		}finally
		{
			return sb.toString();
		}
	}
    public static void main(String args[]) {

    }
}

最後可以回傳資料.