标签: httpurlconnection

在大多数情况下,是什么让 Jsoup 比 HttpURLConnection 和 HttpClient 更快

我想比较标题中提到的三种实现的性能,我写了一个小 JAVA 程序来帮助我做到这一点。main 方法包含三个测试块,每个块看起来像这样:

        nb=0; time=0;
        for (int i = 0; i < 7; i++) {
            double v = methodX(url);
            if(v>0){
                nb++;
                time+=v;
            }
        }
        if(nb==0) nb=1;
        System.out.println("HttpClient : "+(time/ ((double) nb))+". Tries "+nb+"/7");
Run Code Online (Sandbox Code Playgroud)

变量nb用于避免失败的请求。现在方法methodX是以下之一:

    private static double testWithNativeHUC(String url){
        try {
            HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.addRequestProperty("User-Agent", UA);
            long before = System.currentTimeMillis();
            BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while (bufferedReader.readLine()!=null);
            return System.currentTimeMillis()-before;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static double testWithHC(String …
Run Code Online (Sandbox Code Playgroud)

java optimization httpclient httpurlconnection jsoup

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

android,如何将用户名和密码作为标题字段发送到webservice?

我正在尝试在Android手机上创建一个从用户获取用户名和密码的应用程序,使用md5加密密码,然后使用这些参数连接到url.

一个连接的代码在iphone上工作正常,但我在android中找不到类似的东西:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:myURL];

[request setHTTPMethod:@"GET"];

[request addValue:usernameField.text forHTTPHeaderField:@"UserName"];

[request addValue:MD5Pass2 forHTTPHeaderField:@"Password"];
Run Code Online (Sandbox Code Playgroud)

我试图通过httpurlconnection连接使用post/get Dataoutputstream,httpclient发送参数httpget/httppost,但没有成功.

我想我需要将参数作为headerfield发送,但我不知道如何.

注意:我比较了加密结果,这是正确的.

android httpclient httpurlconnection http-headers

0
推荐指数
1
解决办法
3781
查看次数

HttpUrlConnection android

我是新的android开发人员.

我正在尝试使用此代码从我的网络服务器访问数据....

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    URL url;
    try {
        url = new URL("http://www.mysite.net/LEDstate.txt");

        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            //System.out.print(current);


            TextView t = (TextView) findViewById(R.id.ledstate);

            t.setText(current); 
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return …
Run Code Online (Sandbox Code Playgroud)

android httpurlconnection

0
推荐指数
1
解决办法
2798
查看次数

如何让我的HttpUrlConnection以JSON格式返回数据?

我有一个HttpUrlConnectionJava应用程序和一个Web应用程序.在Java应用程序上,我有代码:

exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length);
exchange.getResponseHeaders().set("content-type", "application/json");
exchange.getResponseBody().write(response.getBytes());
exchange.close();
Run Code Online (Sandbox Code Playgroud)

我认为错误的代码在第二行,但我无法弄清楚我应该怎么做.交换是类型的HttpExchange.

字符串响应包含: { batteryMax: 22000, batteryCharge: 860, carRange: 350 }

我使用以下代码检索数据:

var jsonData;
var jqxhr = $.getJSON("http://145.93.73.69:8080/getInfo", function(data) {
    jsonData = data
})
.error(function() { alert("error"); });
Run Code Online (Sandbox Code Playgroud)

error总是得到警报,jsonData保持未定义和jqxhr.responseText包含{ batteryMax: 22000, batteryCharge: 860, carRange: 350 }.

为了使这项工作,我需要改变什么?

java jquery json get httpurlconnection

0
推荐指数
1
解决办法
411
查看次数

如何在JAVA中保存来自HTTPS网址的文件?

我正在尝试使用outputstream从URL保存文件.该URL由https保护.所以当我尝试获取以下文件时出现了一些错误

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at java.net.URL.openStream(Unknown Source) 
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 60 more
Run Code Online (Sandbox Code Playgroud)

假设我想从这个URL打开文件

https://www.filepicker.io/api/file/KW9EJhYtS6y48Whm2S6D?signature=4098f262b9dba23e4766ce127353aaf4f37fde0fd726d164d944e031fd862c18&policy=eyJoYW5kbGUiOiJLVzlFSmhZdFM2eTQ4V2htMlM2RCIsImV4cGlyeSI6MTUwODE0MTUwNH0=
Run Code Online (Sandbox Code Playgroud)

所以我做了类似的事情:

try{    
    URL URL = new URL('https://www.filepicker.io/api/file/KW9EJhYtS6y48Whm2S6D?signature=4098f262b9dba23e4766ce127353aaf4f37fde0fd726d164d944e031fd862c18&policy=eyJoYW5kbGUiOiJLVzlFSmhZdFM2eTQ4V2htMlM2RCIsImV4cGlyeSI6MTUwODE0MTUwNH0=');
    String = path = "D://download/";
    InputStream ins = url.openStream();
    OutputStream ous = …
Run Code Online (Sandbox Code Playgroud)

java https outputstream httpurlconnection filepicker.io

0
推荐指数
1
解决办法
6284
查看次数

使用HttpUrlConnection与齐射

我到处都读到凌空将使用HttpUrlConnection用于较新版本的api或HttpClient用于旧版本,我试图告诉凌空只使用HttpUrlConnection.

我的主要目标是使用我存储的cookie设置volley来执行请求,为此我知道我需要使用cookie设置HttpUrlConnection,然后将其传递给volley以用作默认实现.

到目前为止这么好,但我不知道如何启动HttpUrlConnection并添加cookie.

有人可以给我一个小例子,说明如何初始化HttpUrlConnection并为其添加一个cookie,然后将其传递给凌空?

我能够在HttpUrlConnection上执行这样的请求并且它有效,但是如何将其设置为与凌空一起使用?

URL urlLink = new URL(url2);
HttpURLConnection conenction = (HttpURLConnection)urlLink.openConnection();
conenction.setRequestProperty("Cookie", cookie);
Run Code Online (Sandbox Code Playgroud)

android httpurlconnection android-volley

0
推荐指数
1
解决办法
4353
查看次数

如何在Android中实现使用HttpURLConnection和PHP服务器登录

我有一个Web服务,它具有登录功能,连接到PHP后端:

Htp://hfbhgvbbnvhn.com/mypictures/loginService.php(实际上是http)

我必须向它发送两个参数,作为回报,我将获得JSONObject.但是现在我正在尝试使用HttpUrlConnection对象连接到PHP服务,但我不知道如何发送参数.我已经搜索了很多解决方案,但他们都在使用DefaultHttpClient处理NameValuePair,我认为我必须发送两个单独的字符串作为参数.那么如何将此代码转换为使用HttpURLConnection而不是DefaultHttpClient的实现,现在在Api 22中不推荐使用DefaultHttpClient?

android web-services httpurlconnection

0
推荐指数
1
解决办法
9921
查看次数

HttpURLConnection PHP 脚本未获取数据

我尝试了许多不同的方法来尝试使用 HttpURLConnection 将数据从我的 Android 应用程序上传到我服务器上的 PHP 脚本,但在服务器上由 PHP 创建的文件中没有显示任何内容。我使用 HTTPClient 取得了成功,但我不得不切换到使用 HttpURLConnection。应用程序在运行时不会崩溃。我确信我忽略了一些简单的东西。我的 PHP 脚本运行良好,甚至返回了预期的响应,但我的 Android 代码有一些我还没有看到的错误。任何帮助表示赞赏。

这是 PHP 脚本的开头:

  $data = $_POST["deviceSIG"];
Run Code Online (Sandbox Code Playgroud)

这是我用来将数据上传到 PHP 脚本的代码:

// the string deviceSIG is defined elsewhere and has been defined in the class.

private class MyAsyncTask extends AsyncTask<String, Integer, String>{
            @Override
            protected String doInBackground(String... params)           
     try{
                URL url = new URL("http://192.168.10.199/user_script.php");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.connect();             

                OutputStream outputStream = conn.getOutputStream();
                OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                writer.write(deviceSIG);
                writer.close(); …
Run Code Online (Sandbox Code Playgroud)

php android httpurlconnection

0
推荐指数
1
解决办法
3222
查看次数

为什么BufferedInputStream一次读取最多2048个字节?

我正在尝试使用我的Android应用程序HttpUrlConnection中的网络读取文件AsyncTask.

虽然我注意到文件下载工作的速度比它应该有的慢一点,因为我使用的网络速度更快.

所以我检查并发现该BufferedInputStream对象一次最多只能读取2048个字节.没有我设置的缓冲区大小.甚至内部默认缓冲区大小为BufferedInputStream8192字节.

我在这里添加我的代码以供参考.

private class DownloadFileTask extends AsyncTask<String, Integer, String> {

  @Override
  protected String doInBackground(String... params) {
    HttpURLConnection connection = null;
    BufferedInputStream input = null;
    OutputStream output = null;
    int lengthOfFile;
    int totalBytesDownloaded = 0;
    int count;
    final int bufferSize = 8 * 1024; // 8KB
    try {
      // Create the URL
      URL url = new URL(params[0]);
      // Open connection
      connection = (HttpURLConnection) url.openConnection();
      // Get the file length
      lengthOfFile = …
Run Code Online (Sandbox Code Playgroud)

java io android bufferedinputstream httpurlconnection

0
推荐指数
1
解决办法
1171
查看次数

使用 HttpURLConnection 将 Json 数据发布到 REST API 服务器

我尝试制作一个小应用程序,它获取相机位图和其他数据并将它们以 Json 格式发送到 REST API 服务器。到目前为止,我已经编写了下面的代码,但我收到错误代码 400 Bad request :(

这是在 MainActivity 中

private void SendPictureToServer(String sPhoto) {

try {
    String baseUrl = "http://192.168.0.1:7100/api/v1/save/img";
    String username = "52363cc0cb3a442ebc98ba399f47ca3d";  // <= api key
    String password = "";

    JSONObject postData = new JSONObject();
    postData.put("pl", "1");
    postData.put("id", "76885");
    postData.put("name", "photo");
    postData.put("ext", "jpg");
    postData.put("type", "Product picture #1");
    postData.put("img", sPhoto);

    ApiClient apiClient = new ApiClient(baseUrl, username, password);
    AsyncTask<Void, Void, String> execute = new ExecuteNetworkOperation(apiClient, postData.toString(), "POST");
    execute.execute();
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

} …

java api android json httpurlconnection

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

将URL对象转换为HttpURLConnection

我是java新手,我还在处理基本主题.通过调用URL.openConnection()并将结果转换为HttpURLConnection,我无法理解以下行在获取新的HttpURLConnection时如何工作.

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Run Code Online (Sandbox Code Playgroud)

如果URL类不从HttpURLConnection继承,如何使用URL对象实例化HttpURLConnection?

根据java API参考,这是两个类的层次结构:

Java.lang.Object⇒java.net.URLConnection⇒java.net.HttpURLConnection

java.lang.Object⇒java.net.URL

据我所知,铸件的使用方式如下:

在这种情况下,HttpURLConnection是URLConnection和Object的后代.因此,HttpURLConnection是一个URLConnection,也是一个Object.

反过来不一定正确:URLConnection可能是HttpURLConnection,但不一定如此.所以你必须使用铸造.

但URL类和HttpURLConnection不相关.只有通过OBJECT类.

这是我无法理解的.有人能帮我吗?

先感谢您.

java url android casting httpurlconnection

-2
推荐指数
1
解决办法
1708
查看次数