标签: httpurlconnection

URLConnection没有得到charset

我正在使用URL.openConnection()从服务器下载的东西.服务器说

Content-Type: text/plain; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

connection.getContentEncoding()回报null.怎么了?

java content-type http urlconnection httpurlconnection

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

Android中的HttpUrlConnection设置范围将被忽略

我正在尝试使用Android从我的服务器获得206响应.

这是代码.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                URL url = new URL("http://aviddapp.com/10mb.file");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestProperty("Range", "bytes=1-2");
                urlConnection.connect();

                System.out.println("Response Code: " + urlConnection.getResponseCode());
                System.out.println("Content-Length: " + urlConnection.getContentLength());
                Map<String, List<String>> map = urlConnection.getHeaderFields();
                for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                    System.out.println("Key : " + entry.getKey() +
                            " ,Value : " + entry.getValue());
                }
                InputStream inputStream = urlConnection.getInputStream();
                long size = 0;

                while(inputStream.read() != …
Run Code Online (Sandbox Code Playgroud)

java android httpurlconnection

19
推荐指数
2
解决办法
1742
查看次数

HttpUrlConnection中的错误流

我想对我自己编写的HTTP Servlet发出POST请求.良好的情况(HTTP响应代码200)始终使用URL.openConnection()方法正常工作.但是当我收到所需的错误响应代码(例如400)时,我想我必须使用HttpUrlConnection.getErrorStream().但ErrorStream对象为null虽然我在错误情况下从servlet发回数据(我想评估此数据以生成错误消息).这就是我的代码:

HttpURLConnection con = null;
        try {
            //Generating request String
            String request = "request="+URLEncoder.encode(xmlGenerator.getStringFromDocument(xmlGenerator.generateConnectRequest(1234)),"UTF-8");
            //Receiving HttpUrlConnection (DoOutput = true; RequestMethod is set to "POST")
            con = openConnection();
            if (con != null){
                PrintWriter pw = new PrintWriter(con.getOutputStream());
                pw.println(request);
                pw.flush();
                pw.close();
                InputStream errorstream = con.getErrorStream();

                BufferedReader br = null;
                if (errorstream == null){
                    InputStream inputstream = con.getInputStream();
                    br = new BufferedReader(new InputStreamReader(inputstream));
                }else{
                    br = new BufferedReader(new InputStreamReader(errorstream));
                }
                String response = "";
                String nachricht;
                while ((nachricht = br.readLine()) != null){ …
Run Code Online (Sandbox Code Playgroud)

httpurlconnection

18
推荐指数
4
解决办法
3万
查看次数

cURL和HttpURLConnection - 发布JSON数据

如何使用HttpURLConnection发布JSON数据?我在尝试这个:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

StringReader reader = new StringReader("{'value': 7.5}");
OutputStream os = httpcon.getOutputStream();

char[] buffer = new char[4096];
int bytes_read;    
while((bytes_read = reader.read(buffer)) != -1) {
    os.write(buffer, 0, bytes_read);// I am getting compilation error here
}
os.close();
Run Code Online (Sandbox Code Playgroud)

我在第14行遇到编译错误.

cURL请求是:

curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{'value': 7.5}" \
"a URL"
Run Code Online (Sandbox Code Playgroud)

这是处理cURL请求的方法吗?任何信息对我都非常有帮助.

谢谢.

java post json curl httpurlconnection

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

如何阅读HttpURLConnection的完整回复?

我在andorid中创建一些修改http标头的代理服务器,它工作正常,但我必须将完整响应转发到'顶层'.
我如何从HttpURLConnection读取整个响应(所有标题,内容,所有内容)?

HttpURLConnection httpURLConnection;
URL url = new URL(ADDRESS);
httpURLConnection = (HttpURLConnection) url.openConnection();
// add headers, write output stream, flush
if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK)
{
    Map<String, List<String>> map = httpURLConnection.getHeaderFields();
    System.out.println("Printing Response Header...\n");

    for (Map.Entry<String, List<String>> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
    }

    return new DataInputStream(httpURLConnection.getInputStream());
}
Run Code Online (Sandbox Code Playgroud)

在getInputStream中我只收到内容,可能有一些整个reposne的流?

java httpurlconnection

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

HttpURLConnection实现

我已经读过HttpURLConnection支持持久连接,因此可以为多个请求重用连接.我尝试了它,发送第二个POST的唯一方法是第二次调用openConnection.否则我得到一个IllegalStateException("已经连接"); 我使用了以下内容:

try{
URL url = new URL("http://someconection.com");
}
catch(Exception e){}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//set output, input etc
//send POST
//Receive response
//Read whole response
//close input stream
con.disconnect();//have also tested commenting this out
con = (HttpURLConnection) url.openConnection();
//Send new POST
Run Code Online (Sandbox Code Playgroud)

第二个请求是通过相同的TCP连接发送的(用wireshark验证它)但我无法理解为什么(虽然这是我想要的)因为我已经调用了disconnect.我检查了HttpURLConnection的源代码,并且实现确实保持了对相同目标的连接的keepalive缓存.我的问题是,在发送第一个请求后,我无法看到连接如何放回缓存中.断开连接关闭连接,没有断开连接,我仍然无法看到连接如何放回缓存.我看到缓存有一个run方法来遍历所有空闲连接(我不确定它是如何被调用的),但我找不到连接如何放回缓存中.似乎唯一发生的地方是httpClient的完成方法,但是没有调用带响应的POST.谁可以帮我这个事?

编辑 我的兴趣是,对于tcp连接重用,HttpUrlConnection对象的正确处理是什么.应该关闭输入/输出流,然后是url.openConnection(); 每次发送新请求(避免disconnect())?如果是,我第二次调用url.openConnection()时无法看到连接是如何重用的,因为第一个请求已从缓存中删除了连接,但无法找到返回的连接方式.是否有可能连接没有返回到keepalive缓存(bug?),但操作系统尚未发布tcp连接,在新连接上,OS返回缓冲连接(尚未发布)或类似的东西? EDIT2 我找到的唯一相关内容来自JDK_KeepAlive

...当应用程序在URLConnection.getInputStream()返回的InputStream上调用close()时,JDK的HTTP协议处理程序将尝试清理连接,如果成功,则将连接放入连接缓存以供将来的HTTP请求重用.

但我不确定这是哪个处理程序.sun.net.www.protocol.http.Handler没有做任何缓存,因为我看到谢谢!

java network-programming jdk1.6 httpurlconnection

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

Tomcat,HTTP Keep-Alive和Java的HttpsUrlConnection

我有两个Tomcat服务器需要维持持久连接以减少SSL握手.一台服务器(代理)位于DMZ中,而另一台服务器安全地位于另一台防火墙后面.代理基本上只运行一个简单的servlet,在将请求转发到安全机器之前进行一些健全性检查.在初始请求中,机器在执行实际工作之前交换证书.因此,我希望在几分钟的超时时间内保持持久连接.

要与安全服务器通信,代理上的servlet使用HttpsUrlConnection.我已经设置了WireShark,我注意到无论keepAliveTimeout我在安全机器上为连接器设置了什么值,TCP连接在大约5或10秒后关闭.这个数字似乎与我所读到的是默认超时以及Java如何处理HTTP Keep-Alive.此链接说明Java Keep-Alive如果服务器发送超时则表示超时,否则在关闭连接之前使用5秒(直接连接)或10秒(代理连接).

我想弄清楚的是如何强制Tomcat发送Keep-Alive标头.不Connection: Keep-Alive,但是Keep-Alive: timeout=x.

我已经尝试过Apache HTTP服务器并修改keepAliveTimeouthttpd.conf确实会导致Keep-Alive标头更改其超时值.此外,Java确实遵守此超时.

更新(12/23/11):在运行了几个实验之后,我尝试使用Apache的HttpClient(3.1)而不是使用Apache的HttpClient(3.1)来编写一些快速而脏的代码HttpsUrlConnection.看来HttpClient在设置为使用Keep-Alive时,只是等待服务器关闭连接.我不知道它会等多久.我正在拍摄以保持HTTP连接活动3到5分钟.

java tomcat keep-alive httpurlconnection

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

我可以全局设置HTTP连接的超时吗?

我有一个程序javax.xml.ws.Service用于调用由WSDL定义的远程服务.此程序在Google App Engine上运行,默认情况下,将HTTP连接超时设置为5秒{1}.我需要增加此超时值,因为此服务通常需要很长时间才能响应,但由于此请求未进行URLConnection,我无法弄清楚如何调用URLConnection.setReadTimeout(int){2}或以其他方式更改超时.

有没有办法在App Engine上全局设置HTTP连接超时?而且,为了分享知识,人们将如何解决这类问题呢?

{1}:https://developers.google.com/appengine/docs/java/urlfetch/overview#Requests

{2}:http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout(int)

java google-app-engine wsdl urlconnection httpurlconnection

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

Android的HttpURLConnection在HEAD请求上抛出EOFException

这个小代码片段可以在Mac的JVM上正常运行.不幸的是,它在Android 4.2上执行时崩溃了.

import java.net.HttpURLConnection;
import java.net.URL;

public class App
{
    public static void main( String... arguments ) throws Exception
    {
        HttpURLConnection connection = (HttpURLConnection) new URL( "https://github.com" ).openConnection();
        connection.setRequestMethod( "HEAD" );

        System.out.println( connection.getResponseCode() + "" );
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我更换https://github.comhttps://www.facebook.com它工作正常,但我无法找出原因.

该例外不包含消息; 所以这里至少是堆栈跟踪.

java.io.EOFException
        at java.util.zip.GZIPInputStream.readFully(GZIPInputStream.java:206)
        at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:98)
        at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
        at libcore.net.http.HttpEngine.initContentStream(HttpEngine.java:541)
        at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:844)
        at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
        at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:495)
        at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
Run Code Online (Sandbox Code Playgroud)

java android http urlconnection httpurlconnection

17
推荐指数
1
解决办法
6825
查看次数

维护HttpUrlConnection调用之间的会话(本机/ Webview)

让我从我想要的开始:

我想制作一个应用程序part native and part webviews.

问题 - 维护本机和Webview部件之间的会话.

处理这个的方法:

我打算实现一个本机登录,在其中我向用户提供两个EditTextboxes和一个按钮,用户输入凭据,我将它们作为JSON发布到服务器.

服务器响应成功或错误.基于Success标志,我读取了此连接的标头值并解压缩SessionCookie:

switch (responseCode) {
                case 200:

                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                   //IF SUCCESS

                    Map<String, List<String>> map = conn.getHeaderFields();

                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
                    }

                    SSID = map.get("Set-Cookie").toString();
                    SSID = SSID.substring(1,SSID.length()-1);
                    return response.toString(); …
Run Code Online (Sandbox Code Playgroud)

php java session android httpurlconnection

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