码迷,mamicode.com
首页 > 编程语言 > 详细

java Http编程小结

时间:2015-08-12 21:33:04      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

1:什么是HTTP?

超文本传输协议(HyperText Transfer Protocol -- HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议。
HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。

2:HTTP编程

1>:使用get方式获取服务器端的一张图片,放在本地==》获取服务器的东西用get方式更好

技术分享
package get;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil
{

    /**
     * 使用get方式获取服务器端的一张图片
     * @throws IOException 
     */
    public static InputStream getInputStream(String path) throws IOException
    {
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //设置请求方式
        con.setRequestMethod("GET");//默认请求方式是get
        //设置连接超时时间
        con.setConnectTimeout(5000);
        //设置可以从服务器端读取数据
        con.setDoInput(true);//默认值就是true
        
        InputStream in = null;
        //判断服务器端的响应码是否是200
        if(con.getResponseCode()==200)
        {
            in = con.getInputStream();
        }
        return in;
    }
    
    public static void makeImg(InputStream in) throws IOException
    {
        FileOutputStream fos = new FileOutputStream("file\\img.jpg");
        byte[] b = new byte[1024];
        int len = 0;
        //读取服务器返回的图片数据
        while ((len = in.read(b))!=-1)
        {
            fos.write(b,0,len);
            
        }
        fos.close();
        in.close();
        
    }
}
面向对象代码
技术分享
package get;

import java.io.IOException;

public class Test
{

    public static void main(String[] args) throws IOException
    {
        String path ="http://localhost:9999/day16/img2.jpg";
        HttpUtil.makeImg(HttpUtil.getInputStream(path));
    }

}
客户端

2:使用post方式提交用户名和密码,并获取服务器端的验证结果==》需要返回数据就用post,服务器端代码上篇博客中有

技术分享
package post;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class HttpUtil
{
    public static String sendByPost(String path,Map<String,String> params,String encode) throws ClientProtocolException, IOException
    {
        //先把要提交的每对儿数据封装成NameValuePair类型的
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        
        for(Map.Entry<String, String> en:params.entrySet())
        {
            list.add(new BasicNameValuePair(en.getKey(),en.getValue()));
        }
        //把要提交的数据组织成提交的格式
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
        //创建提交方式对象
        HttpPost post = new HttpPost(path);
        post.setEntity(entity);
        //创建执行提交的对象
        HttpClient client = new DefaultHttpClient();
        
        //执行提交
        HttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode()==200)
        {
            InputStream in = response.getEntity().getContent();
            return getResult(in,encode);
        }
        return null;
    }

    private static String getResult(InputStream in, String encode) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] arr = new byte[1024];
        int len = 0;
        while((len = in.read(arr))!=-1)
        {
            bos.write(arr,0,len);
        }
        return new String(bos.toByteArray(),encode);
    }
}
面向对象代码
技术分享
package post;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Test
{

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException
    {
        Map<String,String> params = new HashMap<String, String>();
        params.put("username", "李鹏");
        params.put("pwd","123456");
        String path = "http://localhost:9999/day16/servlet/LoginServlet";
        String encode= "utf-8";
        System.out.println(HttpUtils.sendByPost(path, params, encode));

    }

}
客户端

3:使用apache中jar包提供的简介方法提交用户名和密码,并获取服务器端的验证结果

技术分享
package apache;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtil {
    
    public static String sendByPost(String path,HashMap<String,String> params,String encode) throws ClientProtocolException, IOException
    {
        //先把要提交的每对儿数据封装成NameValuePair类型的
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        
        for(Map.Entry<String, String> en:params.entrySet())
        {
            list.add(new BasicNameValuePair(en.getKey(),en.getValue()));
        }
        //把要提交的数据组织成提交的格式
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
        //创建提交方式对象
        HttpPost post = new HttpPost(path);
        post.setEntity(entity);
        //创建执行提交的对象
        HttpClient client = new DefaultHttpClient();
        
        //执行提交
        HttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode()==200)
        {
            InputStream in = response.getEntity().getContent();
            return getResult(in,encode);
        }
        return null;
    }

    private static String getResult(InputStream in, String encode) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] arr = new byte[1024];
        int len = 0;
        while((len = in.read(arr))!=-1)
        {
            bos.write(arr,0,len);
        }
        return new String(bos.toByteArray(),encode);
    }

}
面向对象代码
技术分享
package appache;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Test
{

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException
    {
        Map<String,String> params = new HashMap<String, String>();
        params.put("username", "李鹏");
        params.put("pwd","123456");
        String path = "http://localhost:9999/day16/servlet/LoginServlet";
        String encode= "utf-8";
        System.out.println(HttpUtil.sendByPost(path, params, encode));

    }

}
客户端代码

 

java Http编程小结

标签:

原文地址:http://www.cnblogs.com/lipeng0824/p/4725443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!