Java httpPost 转换为 .asp 形式
在Java中,如果我想将数据发送到服务器上的表单,其中表单类型为:
<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>
在这种情况下,我必须使用HttpPost方法,因为表单接受方法“post”,如表单定义(初始化)中所述:
<form method="**post**" id="form1" name="form1" action="">
在我的示例(android 解决方案)中,我使用这些
__VIEWSTATE
__EVENTTARGET
__EVENTARGUMENT
ctl00$tbUsername
ctl00$tbPwd
ctl00$chkRememberLogin
ctl00$cmdLogin
值,因为它们是服务器发布帖子所需的一次。如果您没有对服务器进行编程,我在哪里可以找到服务器所需的内容?我使用 WireShark 软件来查看客户端和服务器之间的所有传入响应或传出请求,只需使用 http 过滤器 仅查看 http 事务。然后使用任何浏览器以通常的方式登录,就像在线登录一样,然后在 WireShark 中您将看到浏览器和服务器之间的所有请求和响应。通过已知的 IP 地址或主机地址找到您感兴趣的交易,然后在任何交易上单击右键时复制您找到的可读字节。因此,当您这样做时,您会发现对服务器的请求必须是什么样子以及需要哪些值。 回到编码(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;
}
这里我将值发布到我事先知道的URL。
添加标头
httppost.addHeader("Referer",
"http://website/login.asp");
您可以使用超时值
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
int timeoutConnection = 5000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
到请求中。在这种情况下,最好在发生超时时捕获异常并再次发出请求,正如 HttpClient 文档中建议的那样。
默认情况下,HttpClient 遵循重定向,但可以通过使用以下方式捕获每次重定向发生的情况:
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;
}
}
}
然后在对客户端执行所需的所有操作后,您可以释放客户端连接:
public void shutDownClient() {
client.getConnectionManager().shutdown();
}
这是 HttpClient,不要忘记您也可能使用UrlConnection,以下是显示的差异:
http://www.innovation.ch/java/HTTPClient/urlcon_vs_httpclient.html
所以这取决于您更喜欢使用什么以及什么更适合您的项目。
PS 这个POST解决方案适用于我的项目,但可能不适用于你的项目。先使用Wireshark,然后看看必须向服务器发送什么样的请求。就我而言,就像 viewstate=sdsgdgdfd323&username=dsfngkjfdg&password=dsfsdfsfs..... 但我知道可能还有其他。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
URL 是否接受 PUT 代替 POST 完全取决于服务器。
大多数需要 POST 的服务器将只接受 POST。 PUT 的使用要少得多。
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.