标签: urlconnection

Java:如何使用UrlConnection通过授权发布请求?

我想向需要身份验证的服务器生成POST请求.我试着使用以下方法:

private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {

    String data = "product[title]=" + URLEncoder.encode(title) +
                "&product[content]=" + URLEncoder.encode(content) + 
                "&product[price]=" + URLEncoder.encode(price.toString()) +
                "&tags=" + tags;
    try {
        URL url = new URL(urlString);
        URLConnection conn;
        conn = url.openConnection();
        conn.setRequestProperty ("Authorization", "Basic " + encodedString);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush(); 
        // Get the response 
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        String line; 
        while ((line = rd.readLine()) != …
Run Code Online (Sandbox Code Playgroud)

java post authorization urlconnection httpconnection

34
推荐指数
3
解决办法
16万
查看次数

获取"java.net.ProtocolException:服务器重定向次数太多"错误

我正在使用这样的代码创建一个简单的URL请求:

URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
Run Code Online (Sandbox Code Playgroud)

但是在最后一行,我得到了"重定向太多次错误".如果我的"网页"var是google.com,那么它可以正常工作,但是当我尝试使用我的servlet的URL时,它就失败了.我似乎可以通过以下方式调整重定向后的次数(默认为20):

System.setProperty("http.maxRedirects", "100");
Run Code Online (Sandbox Code Playgroud)

但是当我把它调到100时,它肯定需要更长的时间来抛出错误所以我知道它正在尝试.但是,我的servlet的URL在(任何)浏览器中工作正常,并使用firebug中的"persist"选项,它似乎只重定向一次.

关于我的servlet的更多信息...它在tomcat中运行,并使用'mod-proxy-ajp'在apache前面运行.另外值得注意的是,它使用的是表单身份验证,因此您输入的任何URL都应该将您重定向到登录页面.正如我所说,这在所有浏览器中都能正常工作,但由于某些原因,重定向不适用于Java 6中的URLConnection.

感谢阅读...想法?

java url redirect servlets urlconnection

32
推荐指数
2
解决办法
7万
查看次数

Java URLConnection - 我什么时候需要使用connect()方法?

我有一个问题是要理解该类中connect()方法的含义URLConnection.在下面的代码中,如果我使用该connect()方法,如果我不使用它,我会得到相同的结果.

为什么(或何时)我需要使用它?

URL u = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.connect();//with or without it I have the same result

InputStream in = conn.getInputStream();
int b;
while ((b = in.read()) != -1) {
 System.out.write(b);
}
Run Code Online (Sandbox Code Playgroud)

java urlconnection connect httpurlconnection

32
推荐指数
2
解决办法
2万
查看次数

即使httpCon.setRequestMethod("GET"),HttpURLConnection也会发送POST请求; 已设定

这是我的代码:

String addr = "http://172.26.41.18:8080/domain/list";

URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.setRequestMethod("GET");
httpCon.addRequestProperty("Authorization", "Basic YWRtaW4fYFgjkl5463");

httpCon.connect();

OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());

System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());

out.close();
Run Code Online (Sandbox Code Playgroud)

我在回应中看到了什么:

500服务器错误

我打开我的httpConvar,以及我看到的内容:

POST/rest/platform/domain/list HTTP/1.1

为什么它设置为POST,即使我已经习惯httpCon.setRequestMethod("GET");将其设置为GET?

java http urlconnection

28
推荐指数
1
解决办法
3万
查看次数

Java Webstart和URLConnection缓存API

URLConnection缓存API的描述表示为最后一句:

Java 2 Standard Edition中没有URLConnection缓存的默认实现.但是,Java Plugin和Java WebStart确实提供了一个开箱即用的功能.

在哪里可以找到有关Webstart ResponseCache的更多信息?

  • Webstart的哪些版本在哪些平台上激活缓存?
  • 它在哪些情况下有效?只有HTTP获取?
  • 可以配置吗?
  • 源代码是否可用?

背景:

情况1

使用以下(groovy)代码

def url = new URL('http://repo1.maven.org/maven2/')
def connection = url.openConnection()
def result = connection.inputStream.text
Run Code Online (Sandbox Code Playgroud)

我希望每次执行代码时都会联系服务器.但是在执行时

Java Web Start 10.9.2.05
JRE-Version verwenden 1.7.0_09-b05 Java HotSpot(TM) Client VM
Run Code Online (Sandbox Code Playgroud)

行为是不同的.第一次执行代码时,会联系服务器.所有后续的代码执行都不涉及与服务器的任何通信(使用wireshark跟踪).

但它变得更加奇怪.重新启动webstart应用程序后,第一次执行代码时,http://repo1.maven.org/maven2/.pack.gz请求url 导致a 404.仅请求原始网址导致a 304 NOT MODIFIED.所有后续执行都不涉及与服务器的任何通信.

我认为通过缓存功能透明地增强urlconnection的方法很好,很好,有助于提高客户端应用程序的性能.但由于本例中的服务器没有定义Expires头,也没有定义缓存控制头,我认为上面的代码应该总是询问服务器而不是默默地忽略我的请求.

案例2

以下代码在使用webstart 10.1.1.255执行时不起作用(这是由java 7的早期测试版安装的,但我不知道这是哪一个)

URL url = new URL("http://repo1.maven.org/maven2/");
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.connect();
InputStream is = connection.getInputStream();
if ("gzip".equalsIgnoreCase(connection.getContentEncoding()))
{
    is = new …
Run Code Online (Sandbox Code Playgroud)

java caching urlconnection httpurlconnection java-web-start

27
推荐指数
1
解决办法
2902
查看次数

URLConnection FileNotFoundException用于非标准HTTP端口源

我试图使用Apache Ant Get任务来获取我们公司中另一个团队生成的WSDL列表.他们将它们托管在http://.... com:7925/services /上的weblogic 9.x服务器上.我能够通过浏览器访问该页面,但是当尝试将页面复制到本地文件进行解析时,get任务会给我一个FileNotFoundException.我仍然能够(使用ant任务)获得没有HTTP的非标准端口80的URL.

我查看了Ant源代码,并将错误缩小到URLConnection.似乎URLConnection无法识别数据是HTTP流量,因为它不在标准端口上,即使协议被指定为HTTP.我使用WireShark嗅探了流量,并且页面正确地加载了网页,但仍然得到了FileNotFoundException.

这是一个示例,您将看到错误(更改URL以保护无辜者).connection.getInputStream();抛出错误;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

    public class TestGet {
    private static URL source; 
    public static void main(String[] args) {
        doGet();
    }
    public static void doGet() {
            try {
            source = new URL("http", "test.com", 7925,
                    "/services/index.html");
            URLConnection connection = source.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

java ant urlconnection

23
推荐指数
3
解决办法
5万
查看次数

我可以覆盖使用java的HttpUrlConnection类的Host头吗?

我正在使用以下代码在java中打开http连接:

 URL url = new URL("http://stackoverflow.com");
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.setDoOutput(true);
 conn.setRequestMethod("GET");
 conn.setRequestProperty("Host", "Test:8080");
 conn.getOutputStream();
Run Code Online (Sandbox Code Playgroud)

但是,调用conn.setRequestProperty("Host","Test:8080")似乎无效,无论我调用方法的顺序如何,主机都重置为目标服务器.有没有办法在不使用其他库的情况下覆盖Host头?

TIA Matt

java networking http urlconnection httpurlconnection

23
推荐指数
2
解决办法
2万
查看次数

URLConnection不允许我访问有关Http错误的数据(404,500等)

我正在制作一个爬虫,并且需要从流中获取数据,无论它是否为200.CURL正在这样做,以及任何标准浏览器.

以下实际上不会获取请求的内容,即使有一些,也会引发http错误状态代码的异常.我想要输出,是否有办法?我更喜欢使用这个库,因为它实际上会执行持久连接,这对于我正在进行的爬行类型来说是完美的.

package test;

import java.net.*;
import java.io.*;

public class Test {

    public static void main(String[] args) {

         try {

            URL url = new URL("http://github.com/XXXXXXXXXXXXXX");
            URLConnection connection = url.openConnection();

            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            String inputLine;

            while ((inputLine = inStream.readLine()) != null) {
                System.out.println(inputLine);
            }
            inStream.close();
        } catch (MalformedURLException me) {
            System.err.println("MalformedURLException: " + me);
        } catch (IOException ioe) {
            System.err.println("IOException: " + ioe);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

工作,谢谢:这是我想出的 - 就像一个粗略的概念证明:

import java.net.*;
import java.io.*;

public class Test {

    public static …
Run Code Online (Sandbox Code Playgroud)

java urlconnection

21
推荐指数
2
解决办法
3万
查看次数

从URLConnection读取二进制文件

我正在尝试从URLConnection读取二进制文件.当我用文本文件测试它似乎工作正常,但对于二进制文件它没有.发送文件时,我在服务器上使用以下mime-type:

application/octet-stream
Run Code Online (Sandbox Code Playgroud)

但到目前为止似乎没有任何效果.这是我用来接收文件的代码:

file = File.createTempFile( "tempfile", ".bin");
file.deleteOnExit();

URL url = new URL( "http://somedomain.com/image.gif" );

URLConnection connection = url.openConnection();

BufferedReader input = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );

Writer writer = new OutputStreamWriter( new FileOutputStream( file ) );

int c;

while( ( c = input.read() ) != -1 ) {

   writer.write( (char)c );
}

writer.close();

input.close();
Run Code Online (Sandbox Code Playgroud)

java http urlconnection download

20
推荐指数
2
解决办法
4万
查看次数

与Cookie的URLConnection?

我正在尝试创建一个支持cookie的URLConnection.根据我可以使用的文档:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
Run Code Online (Sandbox Code Playgroud)

我无法使用此代码,然后我看到这只适用于API 9(2.3).但是,我在旧的模拟器中使用CookieManager时没有出错,CookieManager存在,但无法构造.有没有办法让这个版本适用于早期版本?我试过了:

            cookieManager.setAcceptCookie(true);
            URLConnection con = u.openConnection();

            con.setRequestProperty("Cookie", cookieManager.getInstance().getCookie(url););
            con.setDoOutput(true);
            con.connect();
            String addCookie = con.getHeaderField("Set-Cookie");
            System.out.println(con.getHeaderFields().toString());
            if (addCookie!=null) {
                cookieManager.getInstance().setCookie(url, addCookie);
            }
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

java cookies android urlconnection

20
推荐指数
1
解决办法
3万
查看次数