简体   繁体   中英

HttpResponse wont work

So when i try to run the following code i can never ever get past the response line. what am i doing wrong? I have allowed internet access in my manifest file. I must be missing something huge because ive seen about 100 similar examples that have the exact same code as i do. I've even built sample projects just to run these few lines and they all act the same way. please please help (the end goal is to make this work with https as well but any progress to make it work with http is good enough for me)

try{

                        HttpClient myHttpClient = new DefaultHttpClient();
                        HttpPost myHttpPost = new HttpPost("http://www.siirretytnumerot.fi/index.html?clientLanguage=eng");
                       //^Ive tried about 10 different sites (http and https) none of them work

                        //NEVER GETS PAST THE LINE BELOW, JUMPS TO THE LAST CATCH BLOCK OF THE EXCEPTION
                        HttpResponse response = myHttpClient.execute(myHttpPost);
                        //NEVER GETS PAST THE ABOVE LINE...

                        String data = EntityUtils.toString(response.getEntity());
                        json= new JSONObject(data);
                    //parse the JSONObject
                       } catch (UnsupportedEncodingException e){e.printStackTrace();}
                         catch (ClientProtocolException e){e.printStackTrace();}
                         catch (IOException e){e.printStackTrace();}
                         catch (JSONException e) {e.printStackTrace();}
                         catch (NullPointerException e){ Log.e("My APP", "exception: " + e.getMessage());}
                         catch (Exception e ) {Log.e("My APP", "exception", e);} 


10-17 15:31:41.423: E/My APP(974): exception
10-17 15:31:41.423: E/My APP(974): android.os.NetworkOnMainThreadException
10-17 15:31:41.423: E/My APP(974):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-17 15:31:41.423: E/My APP(974):  at com.example.httpstuff.MainActivity$1.onClick(MainActivity.java:44)
10-17 15:31:41.423: E/My APP(974):  at android.view.View.performClick(View.java:3511)
10-17 15:31:41.423: E/My APP(974):  at android.view.View$PerformClick.run(View.java:14105)
10-17 15:31:41.423: E/My APP(974):  at android.os.Handler.handleCallback(Handler.java:605)
10-17 15:31:41.423: E/My APP(974):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 15:31:41.423: E/My APP(974):  at android.os.Looper.loop(Looper.java:137)
10-17 15:31:41.423: E/My APP(974):  at android.app.ActivityThread.main(ActivityThread.java:4424)
10-17 15:31:41.423: E/My APP(974):  at java.lang.reflect.Method.invokeNative(Native Method)
10-17 15:31:41.423: E/My APP(974):  at java.lang.reflect.Method.invoke(Method.java:511)
10-17 15:31:41.423: E/My APP(974):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-17 15:31:41.423: E/My APP(974):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 15:31:41.423: E/My APP(974):  at dalvik.system.NativeStart.main(Native Method)

Perfect, that's what I was looking for. Looking up NetworkOnMainThreadException, we get this page . What it means is that you can't run an HTTP request on the main thread of your app, but only when you target Honeycomb.

So, the easiest way to fix this is to target a different Android version. Maybe 2.3, or up to Jellybean. Another way to solve it is to set up an AsyncTask to run the HTTP request.

If it works for you to target a different Android version, do that. If not, I can help you out with the AsyncTask. However, keep in mind that they highly reccommend that you don't run networking requests on your main thread.

As for AsyncTasks, the best place to turn is always the Android documentation .

The basic idea is that you extend the AsyncTask class, which makes you implement a doInBackground method. Then you create an instance of your new class, and call execute(). Here's a code snippet from the documentation:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}

new DownloadFilesTask().execute(url1, url2, url3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM