我正在处理一个应用程序,它与url连接并从页面检索数据。不幸的是它没有到达我感兴趣的页面。
如何通过Java代码中的GET方法将其重定向到所需的页面?
输出“readline”方法显示我的命中/MRcgi/MRlogin.pl,但我希望转到不同的网址
O / P
<TITLE> Service Core</TITLE>
<script type="text/javascript">
var replace_function = function() {
window.location.replace('/MRcgi/MRlogin.pl?USER=***p&PASSWORD=webauth&PROJECTID=-1');
}
代码 -
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String userPassword = "*****";
String encoding = new String(
org.apache.commons.codec.binary.Base64
.encodeBase64(org.apache.commons.codec.binary.StringUtils
.getBytesUtf8(userPassword)));
((HttpURLConnection) con).setRequestMethod("GET");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization", "Basic " + encoding);
// Send post request
///
// con.setDoOutput(false);
/* DataOutputStream wr = new DataOutputStream(con.getOutputStream());
System.out.println("1111" +wr);
wr.writeBytes(urlParameters);
wr.flush();
wr.close();*/
int responseCode = ((HttpURLConnection) con).getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + con);
//System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
//window.location.replace("");
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
//con.
String inputLine;
StringBuffer response = new StringBuffer();
System.out.println("-----" + in.readLine());
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
//response.append(inputLine);
}
in.close();
答案 0 :(得分:0)
Raz,URL
方法不遵循重定向,并且在指定一些其他HTTP行为时不那么灵活:请求类型,标题等。
我建议您使用Apache HTTP Client代替您的需求。这是an example with authentication from official docs:
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
请注意,如果使用JDK7或更高版本,则可以使用try-with-resources隐式关闭资源。