Android HTTP request

You should make your HTTP request in a separate thread. NetworkOnMainThreadException says that you are trying to make your network operation on the main thread.

docs at developer.android.com

1] Use simple Thread

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            HttpClient httpclient = new DefaultHttpClient(httpParameters);
            HttpPost httppost = new HttpPost("http://bbpf.bplaced.net/insert.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);

        }
    });
    t.start();

2] You can use AsyncTask if you would like to have more control over the task:

    AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            ttpClient httpclient = new DefaultHttpClient(httpParameters);
            HttpPost httppost = new HttpPost("http://bbpf.bplaced.net/insert.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            // Notifies UI when the task is done
            textView.setText("Insert finished!");
        }
    }.execute();

3] Use some networking library (robospice, retrofit) to make writing async network tasks a little easier.

 

 

    public void sendPost(View view) {

        AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            HttpResponse response;

            protected Void doInBackground(Void... params) {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet request = new HttpGet("http://www.weather.com.cn/adat/sk/101010100.html");
                    // replace with your url
                    Log.d("Posting", "creating key pairs");

                    try {
                        response = client.execute(request);

                        Log.d("Response of Post request", response.toString());
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    return null;
                }

            @Override
            protected void onPostExecute(Void aVoid) {
                // Notifies UI when the task is done
                HttpEntity entity = response.getEntity();

                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

                    StringBuilder sb = new StringBuilder();

                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }

                    textView.setText(sb.toString());

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.execute();

    }

 

android httpClient 支持HTTPS的2种处理方式

http://my.oschina.net/blackylin/blog/144136

Https连接,新建两个class, 使用

HttpClient client = new HttpClientHelper().getHttpClient();

代替

HttpClient client = new DefaultHttpClient();

新建class如下

public class HttpClientHelper {

        private HttpClient httpClient;

        private HttpClientHelper() {
        }

        public synchronized HttpClient getHttpClient() {

            if (null == httpClient) {
                // 初始化工作
                try {
                    KeyStore trustStore = KeyStore.getInstance(KeyStore
                            .getDefaultType());
                    trustStore.load(null, null);
                    SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
                    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  //允许所有主机的验证

                    HttpParams params = new BasicHttpParams();

                    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                    HttpProtocolParams.setContentCharset(params,
                            HTTP.DEFAULT_CONTENT_CHARSET);
                    HttpProtocolParams.setUseExpectContinue(params, true);

                    // 设置连接管理器的超时
                    ConnManagerParams.setTimeout(params, 10000);
                    // 设置连接超时
                    HttpConnectionParams.setConnectionTimeout(params, 10000);
                    // 设置socket超时
                    HttpConnectionParams.setSoTimeout(params, 10000);

                    // 设置http https支持
                    SchemeRegistry schReg = new SchemeRegistry();
                    schReg.register(new Scheme("http", PlainSocketFactory
                            .getSocketFactory(), 80));
                    schReg.register(new Scheme("https", sf, 443));

                    ClientConnectionManager conManager = new ThreadSafeClientConnManager(
                            params, schReg);

                    httpClient = new DefaultHttpClient(conManager, params);
                } catch (Exception e) {
                    e.printStackTrace();
                    return new DefaultHttpClient();
                }
            }
            return httpClient;
        }

    }

    class SSLSocketFactoryEx extends SSLSocketFactory {

        SSLContext sslContext = SSLContext.getInstance("TLS");

        public SSLSocketFactoryEx(KeyStore truststore)
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException {
            super(truststore);

            TrustManager tm = new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] chain, String authType)
                        throws java.security.cert.CertificateException {

                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] chain, String authType)
                        throws java.security.cert.CertificateException {

                }
            };

            sslContext.init(null, new TrustManager[] { tm }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                                   boolean autoClose) throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port,
                    autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
    }

5 thoughts on “Android HTTP request

  1. Appreciating the persistence you put into your website and
    in depth information you provide. It’s awesome to come across
    a blog every once in a while that isn’t the same out of date rehashed material.
    Great read! I’ve saved your site and I’m including your RSS feeds
    to my Google account.

  2. I?¦ve been exploring for a little for any high quality articles or blog posts in this sort of space . Exploring in Yahoo I finally stumbled upon this site. Studying this information So i am glad to show that I’ve a very good uncanny feeling I came upon exactly what I needed. I so much for sure will make sure to don?¦t overlook this site and provides it a look regularly.

  3. C’est ca que j’aime dans la blogosphère, c’est un peu comme un petit village ou on se croise ici, on discute, et on se recroise ailleurs D’où l&rsouo;impqrtance d’avoir un bon plugin si on est en dofollow, un plugin qui permette d’identifier à qui on parle

Leave a Reply

Your email address will not be published. Required fields are marked *