`
gaojingsong
  • 浏览: 1150786 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论
阅读更多
   
概述:使用UrlConnection 、Socket以及HttpClient模拟Http请求,
            本地回环IP地址不要以为只有127.0.0.1,
经过测试发现127.0.0.1 ---> 127.255.255.254(去掉0和255) 的范围都是本地回环地址。  所以见到这些奇怪的IP不要惊讶。他们也代表本地IP等价localhost

 
package cn.com.testhttp;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
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.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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
 
@SuppressWarnings("deprecation")
public class HttpDemo {
 
///*
// POST /kafka/servlet/HelloWorld HTTP/1.1
//Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*
//Referer: http://pc-201202011834:8080/kafka/
//Accept-Language: zh-cn
//User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB7.5; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)
//Content-Type: application/x-www-form-urlencoded
//Accept-Encoding: gzip, deflate
//Host: pc-201202011834:8080
//Content-Length: 10
//Connection: Keep-Alive
//Cache-Control: no-cache
//Cookie: JSESSIONID=DA68F6AA45759761250341A4783642A5
/**
 * 模拟Http请求
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
/* valid HTTP methods */
//    private static final String[] methods = {"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"};
 
//PostUrlConnectionMethod();
//getSocket();  
//postSocket();  
 
//getUrlConnectionMethod();
//postUrlConnectionMethod();
 
 
//getHttpClientMethod();
postHttpClientMethod();
}
 
private static void postSocket() throws Exception {
String host = "127.0.1.4";  
int port = 8080;  
Socket socket = new Socket(host, port);  
 String msg ="msg=postSocket&address=SZ";  
StringBuffer sb = new StringBuffer("POST /kafka/servlet/HelloWorld HTTP/1.1").append("\r\n");  
 sb.append("Connection: Keep-Alive").append("\r\n");
  sb.append("Accept: */*").append("\r\n");
  sb.append("Host: xxxxxxx").append("\r\n");
 sb.append("Content-Type: application/x-www-form-urlencoded").append("\r\n");
 sb.append("Content-Length: ").append(msg.getBytes().length).append("\r\n");
  sb.append("\r\n"); 
  sb.append(msg).append("\r\n"); 
  sb.append("\r\n");  
 System.out.println(sb.toString());
    // 发出HTTP请求  
    OutputStream socketOut = socket.getOutputStream();  
    socketOut.write(sb.toString().getBytes());  
    socket.shutdownOutput(); // 关闭输出流  
    // 接收响应结果  
    System.out.println(socket);
  //关闭资源释放链接
}
 
private static void getSocket() throws Exception {
String host = "127.0.1.4";  
int port = 8080;  
Socket socket = new Socket(host, port);  
 String msg ="msg=getSocket&address=SZ";  
StringBuffer sb = new StringBuffer("GET /kafka/servlet/HelloWorld?"+msg+" HTTP/1.1").append("\r\n");  
 sb.append("Connection: Keep-Alive").append("\r\n");
 sb.append("Accept: */*").append("\r\n");
 sb.append("Host: xxxxxxx").append("\r\n");
 sb.append("\r\n");
   System.out.println(sb.toString());
    // 发出HTTP请求  
    OutputStream socketOut = socket.getOutputStream();  
    socketOut.write(sb.toString().getBytes());  
    socket.shutdownOutput(); // 关闭输出流  
    // 接收响应结果  
    System.out.println(socket);
  //关闭资源释放链接
}
 
private static void postUrlConnectionMethod() throws Exception {
URL url = new URL("http://127.0.1.4:8080/kafka/servlet/HelloWorld");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在    http正文内,因此需要设为true, 默认情况下是false;    
httpUrlConnection.setDoOutput(true);   
//设置是否从httpUrlConnection读入,默认情况下是true;   
httpUrlConnection.setDoInput(true);    
        // Post 请求不能使用缓存 
httpUrlConnection.setUseCaches(false); 
//设置超时时间和请求类型
httpUrlConnection.setConnectTimeout(30000);  
httpUrlConnection.setReadTimeout(30000); 
httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   //连接,
httpUrlConnection.connect();  
 
//参数要放在    http正文内
OutputStream out = httpUrlConnection.getOutputStream();
String msg ="msg=Hello&address=SZ";
out.write(msg.getBytes());
out.flush();
out.close();
InputStream in = httpUrlConnection.getInputStream();
//关闭资源释放链接
}
 
private static void getUrlConnectionMethod() throws Exception {
URL url = new URL("http://127.0.1.4:8080/kafka/servlet/HelloWorld?msg=getUrlConnectionMethod&address=SZ");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在    http正文内,因此需要设为true, 默认情况下是false;    
httpUrlConnection.setDoOutput(true);   
//设置是否从httpUrlConnection读入,默认情况下是true;   
httpUrlConnection.setDoInput(true);    
              // Post 请求不能使用缓存 
httpUrlConnection.setUseCaches(false); 
//设置超时时间和请求类型
httpUrlConnection.setConnectTimeout(30000);  
httpUrlConnection.setReadTimeout(30000); 
httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
       //连接,
httpUrlConnection.connect();  
//注意此句代码必须要保留处理请求结果,即使没有结果也要保留否则不会提交
InputStream in = httpUrlConnection.getInputStream();
}
 
/**
 httpcomponents\httpcore\4.4.4\httpcore-4.4.4.jar
httpcomponents\httpclient\4.4.1\httpclient-4.4.1.jar
commons-logging\commons-logging\1.2\commons-logging-1.2.jar
commons-codec\commons-codec\1.9\commons-codec-1.9.jar
 * @throws Exception
 */
private static void getHttpClientMethod() throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://127.0.1.4:8080/kafka/servlet/HelloWorld?msg=getHttpClientMethod&address=SZ");
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
//关闭资源释放链接
}
 
private static void postHttpClientMethod() throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.1.4:8080/kafka/servlet/HelloWorld");
String content ="msg=postHttpClientMethod&address=SZ";
//HttpParams params = new BasicHttpParams();
//params.setParameter("msg", "postHttpClientMethod");
//params.setParameter("address", "WhoAmI");
//httpPost.setParams(params);
 
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("msg","postHttpClientMethod"));
parameters.add(new BasicNameValuePair("address","SZ"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
httpPost.setEntity(ent);
 
HttpResponse response = httpClient.execute(httpPost);
System.out.println(response.getStatusLine());
System.out.println(response.getEntity().toString());
HttpEntity entity = response.getEntity();
//关闭资源释放链接
}
 
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics