Java httpPost 转 .asp 格式 [英] Java httpPost into .asp form

查看:15
本文介绍了Java httpPost 转 .asp 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如果我想将数据发送到服务器上的表单,表单类型是:

 
<div id="login" class="box"><div class="header">登录</div><div class="内容"><label for="txtUser">用户:</label><input id="txtUser" name="txtUser" type="text" size="13" value=""/><label for="txtPassword">密码:</label><input id="txtPassword" name="txtPassword" type="password" size="13" value=""/><input id="BLogin" name="BLogin" type="submit" value="登录"/>

<div class="footer"><input type="checkbox" id="chkSave" name="chkSave"/><label for="chkSave">保存账户</label>

</表单>

在这种情况下,我必须使用 HttpPost 方法,因为表单接受方法post",正如表单定义(初始化)中所述:

在我的示例(android 解决方案)中,我使用的是

__VIEWSTATE__活动目标__事件参数ctl00$tb 用户名ctl00$tbpwdctl00$chkRememberLoginctl00$cmd登录

值,因为它们是服务器发布帖子所需的一次.如果您没有对服务器进行编程,我在哪里可以找到服务器所需的内容?我正在使用 WireShark 软件查看客户端和服务器之间的所有传入响应或传出请求,只需使用 http 过滤器 即可仅查看 http 事务.然后使用任何浏览器以通常的方式登录,就像在线登录一样,然后在 WireShark 中,您将看到浏览器和服务器之间的所有请求和响应.通过已知 IP 地址或主机地址找到您感兴趣的那个,然后复制可读字节,如果您在任何事务上单击右键,就会找到该字节.所以当你这样做时,你会发现你对服务器的请求必须是什么样子以及需要哪些值.回到编码(java):

public HttpResponse httpPost1(String viewstateValue, String url, String username, String password)抛出 ConnectTimeoutException {尝试 {// -  -  -  - 邮政HttpPost httppost = new HttpPost(url);列表nameValuePairs = new ArrayList();nameValuePairs.add(new BasicNameValuePair("__VIEWSTATE",视图状态值));nameValuePairs.add(new BasicNameValuePair("__EVENTTARGET", ""));名称值对.add(new BasicNameValuePair("__EVENTARGUMENT", ""));nameValuePairs.add(new BasicNameValuePair("ctl00$tbUsername",用户名));nameValuePairs.add(new BasicNameValuePair("ctl00$tbPwd", password));nameValuePairs.add(new BasicNameValuePair("ctl00$chkRememberLogin", "0"));nameValuePairs.add(new BasicNameValuePair("ctl00$cmdLogin",登录"));//nameValuePairs.add(new//BasicNameValuePair("ctl00$cmdForgetMe",//忘了我"));httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));response = client.execute(httppost);String responseHtml = EntityUtils.toString(response.getEntity());//System.out.println(responseHtml);//System.out.println(response1.getStatusLine());} catch (ClientProtocolException e) {} catch (IOException e) {}返回响应;}

在这里,我将值发布到我事先知道的 URL.

您可以使用

添加标题

httppost.addHeader("Referer","http://website/login.asp");

或请求的超时值

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));int timeoutConnection = 5000;HttpParams httpParameters = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParameters,超时连接);

在这种情况下,最好在发生超时时捕获异常并再次发出请求,正如 HttpClient 文档中建议的那样.

HttpClient 默认跟随重定向,但每次重定向发生时都可以使用:

private RedirectHandler customRedirectHandler;…………(也许构造函数..)client.setRedirectHandler(customRedirectHandler);…………类 CustomRedirectHandler 扩展 DefaultRedirectHandler {@覆盖public boolean isRedirectRequested(HttpResponse response,HttpContext 上下文) {//System.out.println("isRedirectRequested");返回真;}@覆盖公共 URI getLocationURI(HttpResponse 响应,HttpContext 上下文)抛出协议异常{String location = response.getLastHeader("Location").getValue();如果(位置.包含(登录")){//System.out.println("需要登录");} 别的 {//System.out.println("无需登录");}URI 重定向URI = null;尝试 {redirectURI = 新 URI(位置);} catch (URISyntaxException e) {}返回重定向URI;}}}

然后在对客户端完成您需要的所有操作后,您可能会释放客户端连接:

public void shutdownClient() {client.getConnectionManager().shutdown();}

这是一个 HttpClient 的例子,不要忘记你也可以使用 UrlConnection,这里显示了不同之处:

http://www.innovation.ch/java/HTTPClient/urlcon_vs_httpclient.html

所以这取决于您更喜欢使用什么以及哪种更适合您的项目.

附言这个POST解决方案适用于我的项目,但它可能不适用于您的项目.首先使用Wireshark,然后查看必须向服务器发送什么样的请求.就我而言,它就像 viewstate=sdsgdgdfd323&username=dsfngkjfdg&password=dsfsdfsfs..... 但我知道可能还有其他人.

解决方案

URL 是否接受 PUT 代替 POST 完全取决于服务器.

大多数需要 POST 的服务器只接受 POST.PUT 很少使用.

In Java, if I want to send data to form on the server, where form type is:

 <form method="post" id="form1" name="form1" action="">
 <div id="login" class="box">
  <div class="header">Log in</div>
  <div class="content">
   <label for="txtUser">User:</label>
   <input id="txtUser" name="txtUser" type="text" size="13" value="" />
   <label for="txtPassword">Password:</label>
   <input id="txtPassword" name="txtPassword" type="password" size="13" value="" />
   <input id="BLogin" name="BLogin" type="submit" value="Log in"  />
  </div>
  <div class="footer">
   <input type="checkbox" id="chkSave" name="chkSave"   /> <label for="chkSave">Save account</label>
  </div>
 </div>
 </form>

in this case I must use HttpPost method, since the form accepts the method "post" as it is stated in the form definition(initialization):

<form method="**post**" id="form1" name="form1" action="">

In my example(android solution) i am using the

__VIEWSTATE
__EVENTTARGET
__EVENTARGUMENT
ctl00$tbUsername
ctl00$tbPwd
ctl00$chkRememberLogin
ctl00$cmdLogin

values, since they are the once that are required by the server to make the post. Where do I find what is required by the server in the case when you have not programmed the server? I am using the WireShark software to see all the incomming responses or outgoing requests between the client and the server, just use the http filter to see only the http transactions. Then use any browser to login in the usual way as you do it online and then in WireShark you will see all the requests and responses between your browser and server. Find the one you are interested in by the known IP address or the host address and then copy the readable bytes which you find if you click the right button on any of the transactions. So when you do that, you will find how your request to the server must look like and which values are needed. Back to coding(java):

public HttpResponse httpPost1(String viewstateValue, String url, String username, String password)
            throws ConnectTimeoutException {
            try {
                // --------post
                HttpPost httppost = new HttpPost(url);

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("__VIEWSTATE",
                        viewstateValue));
                nameValuePairs.add(new BasicNameValuePair("__EVENTTARGET", ""));
                nameValuePairs
                        .add(new BasicNameValuePair("__EVENTARGUMENT", ""));

                nameValuePairs.add(new BasicNameValuePair("ctl00$tbUsername",
                        username));
                nameValuePairs.add(new BasicNameValuePair("ctl00$tbPwd", password));
                nameValuePairs.add(new BasicNameValuePair(
                        "ctl00$chkRememberLogin", "0"));
                nameValuePairs.add(new BasicNameValuePair("ctl00$cmdLogin",
                        "Login"));
                // nameValuePairs.add(new
                // BasicNameValuePair("ctl00$cmdForgetMe",
                // "Forget Me"));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = client.execute(httppost);

                String responseHtml = EntityUtils.toString(response
                        .getEntity());
                // System.out.println(responseHtml);
                // System.out.println(response1.getStatusLine());

            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

        return response;
    }

Here i post the values to the URL which i know in advance.

You might add headers using

httppost.addHeader("Referer",
                    "http://website/login.asp");

or time-out value to the request

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            int timeoutConnection = 5000;
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);

In this case it is better to catch the exceptions if the timeout occured and make the request again, as it is advised to do in the HttpClient documentation.

HttpClient follows redirects by default, but it is possible to catch everytime the redirect occurs by using:

private RedirectHandler customRedirectHandler;

........
(maybe constructor..)
    client.setRedirectHandler(customRedirectHandler);
........
class CustomRedirectHandler extends DefaultRedirectHandler {
        @Override
        public boolean isRedirectRequested(HttpResponse response,
                HttpContext context) {
            // System.out.println("isRedirectRequested");

            return true;
        }

        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context)
                throws ProtocolException {

            String location = response.getLastHeader("Location").getValue();

            if (location.contains("Login")) {
                // System.out.println("Login needed");
            } else {
                // System.out.println("No login required");
            }

            URI redirectURI = null;
            try {
                redirectURI = new URI(location);
            } catch (URISyntaxException e) {
            }

            return redirectURI;
        }
    }
}

and then after doing everything that you need with the client you might release your clients connection:

public void shutDownClient() {
    client.getConnectionManager().shutdown();
}

This is an example of the HttpClient, do not forget that you might also use the UrlConnection, here are differences shown:

http://www.innovation.ch/java/HTTPClient/urlcon_vs_httpclient.html

So it depends what you prefer to use and what is more appropriate for your project.

P.S. This POST solution is applied to my project, but it may not work for yours.. Use Wireshark first and then see what kind of requests must be sent to the server. In my case it was like viewstate=sdsgdgdfd323&username=dsfngkjfdg&password=dsfsdfsfs..... but i know that there might be others.

解决方案

Whether or not the URL accepts a PUT in place of a POST depends entirely on the server.

Most servers that expect a POST will accept only a POST. A PUT is used much more rarely.

这篇关于Java httpPost 转 .asp 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Java开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆