JAvaにおけるHttpプロトコルの使用

5552 ワード

新しいクラス:HttpTools.JAva、コードを貼り付けて
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import com.bony.demo.Log;

public class HttpTools {
/**
 *    URL  GET     
 * @author bony
 * @param url      URL
 * @param param     ,        name1=value1&name2=value2    。
 * @return URL             
 */
public static String UA=null,result=null,httpselty=null,message=null;
public static int code=0;
public BufferedReader buffered_reader = null;
public InputStream stream= null;
InputStreamReader stream_reader= null;
//    HttpURLConnection httpUrlConnection= null;
public InputStream sendGet(String url, String param) {
    try {
    	String 	UrlString;
    	if(param!=""&&param!=null)UrlString = url + "?" + param;
    	else UrlString=url;
    	System.out.println(UrlString);
    	URL toURL = new URL(UrlString);
	Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1", 8888));
        URLConnection connection = toURL.openConnection(proxy);//    URL     
//	URLConnection connection = toURL.openConnection();//    URL     
	HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;
	httpUrlConnection.setConnectTimeout(1500);//       
        httpUrlConnection.setReadTimeout(1500);//     
    	httpUrlConnection.setRequestProperty("X-KKBROWSER-UA",UA);
    	httpUrlConnection.setRequestProperty("Content-Type", "application/x-protobuf");   
    	httpUrlConnection.setRequestProperty("Accept", "application/x-protobuf");    
        httpUrlConnection.connect();//    
        code=httpUrlConnection.getResponseCode();//      
	message = httpUrlConnection.getResponseMessage();//    
        stream=httpUrlConnection.getInputStream();//       
	} 
    	catch (Exception e) {
	Log.run.error("sendGet is Exception:"+e.getMessage());
    	System.err.println("sendGet is Exception:"+e.getMessage());
    	}
	return stream;//     
}
/**
 *     URL   POST     
 * @author bony
 * @param url       URL
 * @param param     ,        name1=value1&name2=value2    。
 * @return             
 */
public InputStream sendPost(String url, String param) {
	PrintWriter print_writer=null;
    try {
    	URL toURL = new URL(url);
        Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1", 8888));
        URLConnection connection = toURL.openConnection(proxy);//    URL     
//	URLConnection connection = toURL.openConnection();//    URL     
	HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;//   POST          
        httpUrlConnection.setRequestProperty("X-KKBROWSER-UA",UA);
    	httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");   
	httpUrlConnection.setDoOutput(true);		//    
	httpUrlConnection.setDoInput(true);		//    	            
	httpUrlConnection.setConnectTimeout(1500);	//       
	httpUrlConnection.setRequestMethod("POST");
	httpUrlConnection.setReadTimeout(1500);		//     
        httpUrlConnection.connect();		//    
        OutputStream output_stream = httpUrlConnection.getOutputStream();//     
	print_writer=new PrintWriter(output_stream);		//       
        print_writer.write(param);
	print_writer.flush();		// flush      
	code=httpUrlConnection.getResponseCode();		//      
	message = httpUrlConnection.getResponseMessage();		//    
	httpselty=httpUrlConnection.getRequestMethod();	//      
        stream=httpUrlConnection.getInputStream();		//       
    } 
    catch (Exception e) {
		Log.run.error("sendPost is Exception:"+e.getMessage());
		System.err.println("sendPost is Exception:"+e.getMessage());
//			e.printStackTrace();
    }
	return stream;																		//     
}  
/**
 *   InputStream       
 * @param inputStream
 * @return byte[]
 */
public byte[] getResponseBody(InputStream inputStream) {
	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[2048];
		InputStream is = inputStream;
		for (int i = 0; i != -1; i = is.read(buf))
			baos.write(buf, 0, i);
		return baos.toByteArray();
	} catch (Exception e) {
		return null;
	}
}
/**
 * http        
 * @return
 */
public String getReadline(){
    try {
    	stream_reader=new InputStreamReader(stream);
		buffered_reader=new BufferedReader(stream_reader);	//         
		result=buffered_reader.readLine();								//   (      )
    } 
    catch (Exception e) {
		Log.run.error("get result is Exception:"+e.getMessage());
    	System.err.println("get result is Exception:"+e.getMessage());
    	}
    finally{
        try {if(buffered_reader != null)buffered_reader.close();} 
        catch (Exception e1){
			Log.run.error("getInputStream close is Exception:"+e1.getMessage());
    		System.err.println("getInputStream close is Exception:"+e1.getMessage());
    		}
    }
	return result;//      
}
}

Getリクエストを送信し、返されたデータを読み込む必要がある場合は、次のように呼び出すことができます.
String url="http://baidu.com";
String param="a=1&b=1";
HttpTools http=new HttpTools();//        
http.sendGet(url, param);

Postを送信する必要がある場合
String url="http://baidu.com";
String param="{'a':'1','b':'2'}";
HttpTools http=new HttpTools();//        
http.sendGet(url, param);

要求し、返されたデータを読み出します.次のように呼び出すことができます.