HttpUrlConnection.connect()查询

时间:2017-07-02 19:17:29

标签: httpurlconnection

经过数小时的网络搜索并试图理解文档后,我似乎无法找到解决此问题的方法。

我有一个使用ASyncTask连接到服务器的应用程序我有3个地址到" test"连接。

现在问题是当我使用Myconnection.connect()时,如果没有已知地址或死链接,后台任务就会挂起。

如果使用死链接或死机服务器挂起并且没有收到任何响应,我该如何测试此连接

Logcat中的错误是

package nodomain.myapplication;
import android.os.AsyncTask;
import android.util.Log;

import org.w3c.dom.Text;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by Shab on 02/07/2017.
 */

public class bgWorker extends AsyncTask<Void, Integer, Void> {
    @Override

    protected Void doInBackground(Void...  params)
    {
        String db_Username = "root";
        String db_Password = "";
        String db_Name = "testdb";
        String url1 = "http://10.0.0.2/testdb/connection.php"; //DEAD? (NO RESPONSE)
 (Program Hang until exception is called)
        String url2 = "http://www.google.com";                  //OK RESPONSE 200
        String url3 = "http://localhost/myPage.php";            //NO RESPONSE
        try {
            getResponseCodes(url1);
            getResponseCodes(url2);
            getResponseCodes(url3);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
    }

    private String encodeURLString(String value) {

        String encodedString = "";
        try {

            encodedString = URLEncoder.encode(value, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedString;
    }

    public static int getResponseCodes(String TheURL) throws MalformedURLException,IOException
    {
        URL oUrl = new URL(TheURL);
        HttpURLConnection oHuC = (HttpURLConnection) oUrl.openConnection();
        oHuC.setRequestMethod("HEAD");
        int response = 0;

        try{

            oHuC.connect();
            response = oHuC.getResponseCode();

              if(response == 200)
                 {
                    Log.i("URL IS OK","");
                 }else{
                    Log.i("URL IS NOT OK","");
                 }

            Log.i("", "Status : " + response);

        }catch(IOException e){

            Log.d("URL ERROR" + oUrl, "D");

        }
        return response;
    }

}

正如您所看到的,我收到回复的唯一网址是www.google.com

我的代码如下:

FixedUpdate

即使IF语句测试200 OK的响应,它也只能通过URL IS OK输出来解释来自3 URL的一个响应。

0 个答案:

没有答案