gpt4 book ai didi

java - HttpClient HTTP/1.1 302 对象已移动

转载 作者:行者123 更新时间:2023-12-02 08:05:57 25 4
gpt4 key购买 nike

此代码适用于我的简单测试登录表单。它使用 POST 登录,然后将所有信息从登录 View 打印到屏幕上。但它不适用于我一直在创建此代码的某个特定网站。有什么想法为什么会发生这种情况以及如何解决它吗?

package visualutopiabot;

import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class Main {

public static void main(String[] args) throws Exception {

DefaultHttpClient httpclient = new DefaultHttpClient();
try {

/* POST login */
HttpPost httpost = new HttpPost("http://website.com/login.asp");

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "nnnnick"));
nvps.add(new BasicNameValuePair("password", "pppassswww123"));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);

/* get content*/
HttpGet httpget = new HttpGet("http://website.com/index.asp");

System.out.println("executing request " + httpget.getURI());

// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");


} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}

最佳答案

如果您使用 httpclient 3x

GetMethod默认情况下 followRedirects 标志设置为 true

您可以尝试将 PostMethod 显式设置重定向设置为 true

 PostMethod postMethod = ...;
postMethod.setFollowRedirects(true)

如果您使用 httpcomponents

httpclient.setRedirectStrategy(new DefaultRedirectStrategy());
httpost.getParams().setParameter("http.protocol.handle-redirects",true);

参见http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html#d4e1192了解更多详情

关于java - HttpClient HTTP/1.1 302 对象已移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com