Android将发布数据发送到webservice

这个问题在这里已经有了答案:

  • 我该如何解决android.os.NetworkOnMainThreadException? 49个答案

  • 使用参数调用sendPostRequest(String username, String pass)方法。 您可以从UI线程调用此方法,请求将从不同的线程(嵌入AsyncTask )发送。

    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);
    }
    

    尝试实施这个代码,它应该工作。 如果你的Android版本高于4.0,那么你将不得不强制使用Asyn Task,这样这个http请求就不会在Main Thread上运行。 否则应用程序将崩溃。 如果应用程序使用HTTPGET或HTTPPOST方法并且正在主线程上运行,它将会崩溃。 Asyn TASk是解决方案。

       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);
    

    看看这个和这个。

    您不能在主线程上执行网络操作。 一点Google搜索总是可以帮助你。

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

    上一篇: Android sending post data to webservice

    下一篇: How to fix NetworkonMainThreadException in Android?