JAVA:http发布请求 [英] JAVA: http post request

查看:205
本文介绍了JAVA:http发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须向网络服务发布请求,以使用用户名和密码对用户进行身份验证。

I have to do post request to a web-service to authenticating the user with username and password.

我对以下帖子请求有疑问:

I have a problem with following post request:

public String postTest(String action, ConnectionParametrData [] parameters) {
        Uri.Builder builder = new Uri.Builder().scheme(scheme).authority(authority).path(action);
        uri = builder.build();
        BufferedReader in = null;
        String ans = null;
        HttpPost request = new HttpPost(uri.toString());
        HttpClient defaultClient = new DefaultHttpClient();
        try {
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
            request.setEntity(new UrlEncodedFormEntity(getValuePairs(parameters)));
            HttpResponse response = defaultClient.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8192);
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String newLine = System.getProperty("line.separator");
            while((line = in.readLine()) != null) {
                sb.append(line + newLine);
            }
            ans = sb.toString();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        return ans;
    }

当我执行此方法时,服务器抛出错误,告知请求不是发布请求。

When I executed this method server throws error telling the request is not a post request.

但这种方法完美无缺:

private String makePost(String action, ConnectionParametrData [] parameters) throws IOException {
        StringBuilder urlBuild = new StringBuilder();
        urlBuild.append(scheme).append("://www.").append(authority).append(action);
        URL url = new URL(urlBuild.toString());
        URLConnection urlConnection = url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream());

        String content = getParameters(parameters);
        printout.writeBytes(content);
        printout.flush();
        printout.close();

        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8192);
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String newLine = System.getProperty("line.separator");
        while((line = in.readLine()) != null) {
            sb.append(line + newLine);
        }
        in.close();
        return sb.toString();
    }

我更喜欢使用HttpClient而不是URLConecction,
有没有人知道为什么第一种方法未被批准为POST?

I prefer to use HttpClient than URLConecction, does anybody know why first method is not approved as POST?

推荐答案

public String getPostPage(String postUrl, NameValuePair[] data,
        String cookie)
{
    String html = "";
    PostMethod method = null;
    String contentStr = null;
    try
    {
        method = new PostMethod(postUrl);
        method.addRequestHeader("User-Agent", USER_AGENT);
        method.addRequestHeader("Host", "asqx.moni.gucheng.com");
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        method.addRequestHeader("Referer", "...");
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        method.addRequestHeader("Cookie", cookie);
        method.addRequestHeader("X-MicrosoftAjax", "Delta=true");
        method.addRequestHeader("Pragma", "no-cache");
//            method.addRequestHeader("Accept-Encoding", "gzip, deflate");
        method.addRequestHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
        method.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        method.addRequestHeader("Accept-Language", "zh-cn,zh;q=0.5");
        method.setRequestBody(data);
        int statusCode = client.executeMethod(method);

        if(statusCode == HttpStatus.SC_OK)
        {
            InputStream in = method.getResponseBodyAsStream();
            if (in != null) {
                byte[] tmp = new byte[4096];
                int bytesRead = 0;
                ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
                while ((bytesRead = in.read(tmp)) != -1) {
                    buffer.write(tmp, 0, bytesRead);
                }
                byte[] bt = buffer.toByteArray();
                String gbk = new String(bt, "GBK");
                String utf8 = new String(bt, "UTF-8");
                if (gbk.length() < utf8.length()) {
                    bt = null;
                    bt = gbk.getBytes("UTF-8");
                    html = new String(bt, "UTF-8");
                    html = html.replaceFirst(
                                    "[cC][hH][aA][rR][sS][eE][tT]\\s*?=\\s*?([gG][bB]2312|[gG][bB][kK]|[gG][bB]18030)",
                                    "charset=utf-8");
                } else if (gbk.length() > utf8.length()) {
                    html = buffer.toString();
                } else {
                    html = buffer.toString();
                }
                buffer.close();
                contentStr = new String("abc".getBytes(), "UTF-8");
                contentStr = html;

                in.close();
                in = null;
            }
        }
        else
        {
            contentStr = null;
        }
    } catch (Exception e)
    {
        log.error(e);
    } finally
    {
        if (method != null)
            method.releaseConnection();
    }
    return contentStr;
}

我使用mothod发布并获取返回内容。希望可以帮到你。

I use the mothod to post and get return content. Hope can help you.

这篇关于JAVA:http发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆