Java中的HTTP通信技术详解

时间:2023-03-08 15:48:34

 1、使用HTTP的Get方式读取网络数据

     
Java中的HTTP通信技术详解
class ReadByGet extends Thread{
@Override
public void run(){
URL url = new URL("网址");//如果有参数,在网址中携带参数
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); String line;
StringBuilder builder = new StringBuilder();
while((line=br.readLine())!=null){
builder.append(line);
}
br.close();
isr.cloae();
is.close(); System.out.println(builder.toString);
}
}
public static void main(String[] args){
new ReadByGet().start();
}
Java中的HTTP通信技术详解

      2、使用HTTP的Post方式与网络交互通信  

Java中的HTTP通信技术详解
Class ReadByPost extends Thread{
@override
public void run(){
URL url = new URL("网址");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.addRequestProperty("encoding","UTF-8");
conn.setDoInput(true);
Conn.setDoOutput(true);
conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw); bw.write("向服务器传递的参数");
bw.flush(); InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while((line = br.readLine())!=null){
builder.append(line);
}
//关闭资源
System.out.println(builder.toString);
}
}
public static void main(){
new ReadByPost().start();
}
Java中的HTTP通信技术详解

      3、使用HttpClient进行Get方式通信

            apache有一个HttpClient包
  1. Java中的HTTP通信技术详解
    class Get extends Thread{
    
        HttpClient client = HttpClients.createDefault();
    @Override
    public void run(){ HttpGet get = new HttpGet("http://www.baidu.com"); HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity,"UTF-8"); System.out.println(result); }
    }
    public static void main(String[] args){
    new Get().start();
    }
    Java中的HTTP通信技术详解

          4、使用HttpClient进行Post方式通信

 
Java中的HTTP通信技术详解
class Post extends Thread{
HttpClient cilent = HttpClients.CreateDefault();
@Override
public void run(){
HttpPost post = new HttpPost("网址");
//设置要传的参数
List<BasicNameValuePair> parameters = new ArratList();
parameters.add(new BasicNameValuePair("key","value")); post.setEntity(new UrlEncodeFormEntity(parameters,"UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.roString(entity,"UTF-8"); System.out.println(result); }
}
main(){
new Post().start();
}
Java中的HTTP通信技术详解

参见:http://www.cnblogs.com/rocomp/p/4803864.html