Android sending post data to webservice

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 49 answers

  • Call sendPostRequest(String username, String pass) method with parameters. You can call this method from the UI thread, the request will be sent from a different thread ( AsyncTask is embedded).

    private void sendPostRequest(String givenUsername, String givenPassword) {
    
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... params) {
                String paramUsername = params[0];
                String paramPassword = params[1];
    
                System.out.println("*** doInBackground ** paramUsername "
                    + paramUsername + " paramPassword :" + paramPassword);
    
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(
                    "http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx");// replace with your url
                httpPost.addHeader("Content-type",
                    "application/x-www-form-urlencoded");
                BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
                    "UserId", paramUsername);  // Make your own key value pair
                BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
                    "Password", paramPassword);// make your own key value pair
    
                // You can add more parameters like above
    
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                nameValuePairList.add(usernameBasicNameValuePair);
                nameValuePairList.add(passwordBasicNameValuePair);
    
                try {
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                        nameValuePairList);
                    httpPost.setEntity(urlEncodedFormEntity);
    
                    try {
                        HttpResponse httpResponse = httpClient
                            .execute(httpPost);
                        InputStream inputStream = httpResponse.getEntity()
                            .getContent();
                        InputStreamReader inputStreamReader = new InputStreamReader(
                            inputStream);
                        BufferedReader bufferedReader = new BufferedReader(
                            inputStreamReader);
                        StringBuilder stringBuilder = new StringBuilder();
                        String bufferedStrChunk = null;
                        while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                            stringBuilder.append(bufferedStrChunk);
                        }
    
                        return stringBuilder.toString();
    
                        } catch (ClientProtocolException cpe) {
                            System.out
                                .println("First Exception coz of HttpResponese :"
                                    + cpe);
                            cpe.printStackTrace();
                        } catch (IOException ioe) {
                            System.out
                                .println("Second Exception coz of HttpResponse :"
                                    + ioe);
                            ioe.printStackTrace();
                        }
    
                } catch (UnsupportedEncodingException uee) {
                    System.out
                        .println("An Exception given because of UrlEncodedFormEntity argument :"
                            + uee);
                    uee.printStackTrace();
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
            }
        }
    
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(givenUsername, givenPassword);
    }
    

    Try implementing this code ,it should work. And if your Android version is above 4.0, then you will have to compulsory use Asyn Task , So that this http request do not run on Main Thread. otherwise app will crash. If the app is using HTTPGET or HTTPPOST method and is running on Main Thread ,it will crash. Asyn TAsk is the Solution.

       HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        JSONObject json=new JSONObject();
        HttpPost post = new HttpPost(url1);
    
        try {
            json.put("Key","your value");
            json.put("Key", "Value");
    
    
            StringEntity stringEntity = new StringEntity(json.toString());
    
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            post.setEntity(stringEntity);
    
            response = client.execute(post);
            Log.e("RESPONSE", response.toString());
            String responseBody = EntityUtils
                    .toString(response.getEntity());
             res= responseBody.toString();
    
            Log.e("RESPONSE BODY", responseBody);
    

    have a look at this and this.

    You cannot perform network operations on the main thread. A little googling can always help.

    链接地址: http://www.djcxy.com/p/29534.html

    上一篇: 在jellybean中出现NetworkOnMainThreadException错误

    下一篇: Android将发布数据发送到webservice