码迷,mamicode.com
首页 > Web开发 > 详细

http协议post

时间:2015-10-24 18:47:45      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

post提交,先是给服务器发送请求,然后服务器响应。

这里发送的请求是用户名和密码,如果正确做出响应,错误也是。

首先我们要把用户名和密码用?加到url后面。这里我们要先处理的是这点,然后再获得链接,并且发送请求的操作。然后接收响应。

package com.neusoft.httpdemo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class Post {
    private static String PATH = "http://192.168.1.119:8080/ok/servlet/Login";
    private static URL url = null;

    static {
        try {
            url = new URL(PATH);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 填写url参数,就是用户名和密码。第二个就是字符集
    private static String sendPostMessage(Map<String, String> params,
            String encode) {
        // 用来放入要传递的参数,buffer是不定长的
        StringBuffer buffer = new StringBuffer();
        try {
            if (params != null && !params.isEmpty()) {
                // 遍历map的内容
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    buffer.append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");
                }
                // 删除掉最后一个&号
                buffer.deleteCharAt(buffer.length() - 1);
                // 获得链接
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                // 或得上传信息的长度和长度
                byte[] data = buffer.toString().getBytes();
                // 如果是浏览器会内置http协议,但是我们用java或者用手机访问没有这样的协议
                // 这时候我们要设置请求属性
                // 设置请求体是文本类型
                //application/x-www-form-urlencoded这种方
                //式会把你传入的数据变成key=value的形式用?加到url后面
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
        
                httpURLConnection.setRequestProperty("Content-Length",
                        String.valueOf(data.length));
                // 获得输出流
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(data);
                int responseCode = httpURLConnection.getResponseCode();
                System.out.println(responseCode);
                if (responseCode == 200) {
                    // 因为方法返回的是一个字符串,现在我们获得的是一个
                    // 输入流,所以我们要通过一个方法转换成字符串
                    return changeInputStream(
                            httpURLConnection.getInputStream(), encode);
                }

            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "";

    }

    // 将一个输入流转化为指定编码的字符串
    private static String changeInputStream(InputStream inputStream,
            String encode) {
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] mydata = new byte[1024];
        String result = "";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(mydata)) != -1) {
                    arrayOutputStream.write(mydata, 0, len);
                }
                result = new String(arrayOutputStream.toByteArray());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", "admin");
        map.put("password", "123");

        String resule = sendPostMessage(map, "utf-8");
        System.out.println(resule);
    }

}

 

http协议post

标签:

原文地址:http://www.cnblogs.com/84126858jmz/p/4907191.html

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