标签: httpurlconnection

URLConnection.getContent与HTML文件

当我使用类似的东西:

URL url = new URL(a_url);
URLConnection url_conn = url.openConnection();
Object content = url_conn.getContent();
Run Code Online (Sandbox Code Playgroud)

并且检索的文件的MIME类型是我调试的HTML或XML, content在运行时将包含以下实例:

sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
Run Code Online (Sandbox Code Playgroud)

现在,如果我想instanceof在该实例上使用,我该怎么办?

if (content instanceof PlainTextInputStream)
{
...
}  
else if(content instanceof ImageProducer)
{
...
}
else if(content instanceof ???) {}
Run Code Online (Sandbox Code Playgroud)

java servlets httpurlconnection

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

使用连接后需要调用java.net.HttpURLConnection.disconnect()吗?

java.net.HttpURLConnection在Android上使用(API 16).我使用connect()然后getInputStream()获取InputStream从连接读取数据.在我使用InputStream(即消耗数据)后,我close().

问题是:这是否也会关闭基础HttpURLConnection(就像通过调用disconnect()它一样)?我的猜测不是,但我只是想证实这一点.更一般的问题是:当连接不再有用时,我是否需要调用java.net.HttpURLConnection.disconnect()?

问题是我有一个方法来打开一个HttpURLConnection给定的主机.签名是:InputStream OpenHttpConnection(String stringURL, String method).返回一个InputStream,调用者用来从连接中读取数据,但如果我disconnect()从该方法的主体内调用,则InputStream关闭并变得无用(我已经确认了这一点).但是,如果,在另一方面,是不是当我打电话关闭了连接close()InputStream,从主叫方,那么我就会有浪费资源的连接.

有什么建议?

java android http httpurlconnection

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

在java中手动超时httpurlconnection

我试图以下面的方式超时httpurlconnection

URL urlConnect = new URL(url.toString());
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
urlc.setConnectTimeout(1000*5);
urlc.setReadTimeout(1000*5);
urlc.connect();
Run Code Online (Sandbox Code Playgroud)

但无法连接,它将apache tomcat分配的超时时间超过2分钟而不是5秒时我提供了gthat,在这种情况下如何手动超时httpurlconnection

java timeout httpurlconnection settimeout

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

HttpURLConnection的!Connection.getInputStream是java.io.FileNotFoundException

我创建了一个方法"UPLPAD2"来将文件上传到服务器.将我的文件拆分为数据包(10MB).没关系(100%).但是当我调用getInputStream时,我得到了FileNotFoundException.我想,在循环中,我创建了新的HttpURLConnection来设置"setRequestProperty".这是个问题.这是我的代码:

@SuppressLint("NewApi")
public int upload2(URL url, String filePath,
        OnProgressUpdate progressCallBack, AtomicInteger cancelHandle)
        throws IOException {
    HttpURLConnection connection = null;
    InputStream fileStream = null;  
    OutputStream out = null;
    InputStream in = null;
    HttpResponse response = new HttpResponse();
    Log.e("Upload_Url_Util", url.getFile());
    Log.e("Upload_FilePath_Util", filePath);
    long total = 0;
    try {
        // Write the request.
        // Read from filePath and upload to server (url)
        byte[] buf = new byte[1024];
        fileStream = new FileInputStream(filePath); 
        long lenghtOfFile = (new java.io.File(filePath)).length();
        Log.e("LENGHT_Of_File", lenghtOfFile + "");

        int totalPacket = …
Run Code Online (Sandbox Code Playgroud)

java android filenotfoundexception httpurlconnection

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

从URL检查内容类型

之前我问过这个问题,Evgeniy Dorofeev回答了这个问题.虽然只为直接链接工作,但我接受了他的回答.他刚刚告诉我从直接链接检查内容类型:

String requestUrl = "https://dl-ssl.google.com/android/repository/android-14_r04.zip";
URL url = new URL(requestUrl);
URLConnection c = url.openConnection();
String contentType = c.getContentType();
Run Code Online (Sandbox Code Playgroud)

据我所知,有两种URL类型下载文件:

  • 直接链接.例如:https://dl-ssl.google.com/android/repository/android-14_r04.zip.通过此链接,我们可以直接下载数据并获取文件名,包含文件扩展名(在此链接中,.zip扩展名).所以我们可以知道要下载的文件.您可以尝试从该链接下载.
  • 直接链接.例如:http://www.example.com/directory/download?file = 52378.您是否曾尝试从Google云端硬盘下载数据?从Google云端硬盘下载数据时,它会为您提供非直接链接,例如上面的链接.我们永远不知道链接是否包含文件或网页.另外,我们不知道文件名和文件扩展名是什么,因为这种链接类型不清楚且随机.

我需要检查它是文件还是网页.如果内容类型是文件,我必须下载它.

所以我的问题:

  • 如何从非直接链接检查内容类型?
  • 如此问题的评论所示,HTTP重定向可以解决问题吗?

谢谢你的帮助.

java url content-type httpurlconnection

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

使用Java URLConnection进行Cookie管理

我对Android编程很新,最近获得了成功的HTTP Post请求,只是为了了解我的cookie没有存储在后续的Post/Get请求之间.我浏览了一下interweb,并找到了Android的Apache客户端和Java的HttpURLConnection的几个例子.我没有成功地将这两种方法应用到我当前的课程中,所以我想知道有经验的人是否可以查看我的代码并提供建议.

概括:

  1. 我的初始POST请求成功并经过身份验证.
  2. 我的第二个POST请求不保留初始POST请求中的cookie.
  3. 是否有人为可能选择Apache方法或Java实现的具体实例或原因?两者都是平等的,还是一个提供比另一个更多的能力和灵活性?

感谢任何帮助,谢谢.

webCreate.java

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class webCreate {

    private final String USER_AGENT = "Mozilla/5.0";


    // HTTP GET request
    public void sendGet(String url) throws Exception {

        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
        HttpCookie cookie = new HttpCookie("lang", "en");


        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header …
Run Code Online (Sandbox Code Playgroud)

java cookies android http-post httpurlconnection

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

在Android API 23中使用HttpURLConnection将文件和参数发送到服务器

经过多次尝试我解决了它,有我用来发送参数和图像的代码:

    public class PurchaseAsync extends AsyncTask<String, Void, Boolean> {

    public static final String TAG = PurchaseAsync.class.getSimpleName();
    public PurchaseAsync(ArrayList<CustomItem> parameters, String imageAddress, PurchaseListener listener){
        this.parameters = parameters;
        this.imageAddress = imageAddress;
        this.listener = listener;
        if(this.parameters == null){
            this.parameters = new ArrayList<>();
        }
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> Image path : " + imageAddress);
    }
    private String imageAddress = "";
    // ========== Use HashMap, it works similar to NameValuePair
    ArrayList<CustomItem> parameters = new ArrayList<>();
    private PurchaseListener listener;
    public interface PurchaseListener {
        void execute(int …
Run Code Online (Sandbox Code Playgroud)

post android file-upload multipartform-data httpurlconnection

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

httpurlconnection非法状态异常:已连接

我试图发布参数并从输入流读取重定向的页面,但我不知道任何此异常

Exception in thread "main" java.lang.IllegalStateException: Already connected
    at java.net.URLConnection.setDoOutput(URLConnection.java:900)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.setDoOutput(HttpsURLConnectionImpl.java:455)
    at com.company.Main.main(Main.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Run Code Online (Sandbox Code Playgroud)

码:

try {

        CookieHandler cookieHandler = null;
        CookieManager.setDefault(cookieHandler);


        HttpURLConnection urlConnection = (HttpURLConnection) new URL("site").openConnection();
        InputStream i = new BufferedInputStream(urlConnection.getInputStream());
        StringBuilder stringBuilder =new StringBuilder();


        int c;
        while ((c=i.read())!=-1){
            stringBuilder.append((char)c);
        }

         // for getting the post paramters that is user name and password field
        Pattern p = Pattern.compile("<input name=\"\\w{22}\" type=\"text\" id=\"\\w{22}\" />");
        Matcher matcher = p.matcher(stringBuilder.toString());

        String …
Run Code Online (Sandbox Code Playgroud)

java httpurlconnection

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

获取HTML响应而不是Json响应

我正在获取HTML响应而不是JSON响应.我正在使用以下代码,我收到的HTML响应为bf.readLine().以下代码中是否存在任何问题或此API问题?

String uri = "http://192.168.77.6/Ivr_ABN_API/?id=" + mobile;
    URL url;
    Gson json = null;
    try {
        url = new URL(uri);
        json = new Gson();

        HttpURLConnection connection;
        access_token = db.getAccessTokenFromDB();
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        System.out.println("URL:" + uri);

        connection.setRequestProperty("Content-Type", "application/json");
        int status = connection.getResponseCode();
        resCode = Integer.toString(status);
        System.out.println("status is " + status);
        InputStream in = connection.getInputStream();
        System.out.println("inputStreamer " + in);
        BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        System.out.println("bf.readLine() - " + bf.readLine());

        while ((output = bf.readLine()) != null) {
            JSONObject obj = …
Run Code Online (Sandbox Code Playgroud)

java json httpurlconnection

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

java.net.SocketException:套接字失败:EACCES(权限被拒绝)

我搜索了所有解决方案并应用到我的项目中.但他们没有工作.我已将此权限拒绝.我已将所有可能的权限放入清单文件中.请告诉我我的项目有什么问题.

public static void getGetResponse() {
        InputStream inputStream = null;
        try {
            URL url = new URL("http://120.26.89.113:8080/common/qiniuToken");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");          
            String userPassword = "wehelper:***********";
            byte[] encodedBytes = Base64.encode(userPassword.getBytes(), 0);
            connection.setRequestProperty("Authorization", "Basic " + encodedBytes);
            connection.connect();
            int resCode = connection.getResponseCode();
            if (resCode == 200) {
                inputStream = connection.getInputStream();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            System.out.println(out.toString());//Prints the string content read from input stream …
Run Code Online (Sandbox Code Playgroud)

java android httpurlconnection permission-denied

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