Http Post不工作​​(Android)

时间:2013-11-22 15:13:25

标签: android http-post

我的代码在Android 2.2上工作正常但在Android 4 +上无效。有人知道是什么问题。我在Android模拟器和我的手机上尝试过它.P.S我已经允许上网。

      protected void postData2(){

    HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;   
            String response = null;         
            String parameters = "Post Data Here";   


            try
            {

                url = new URL ("URL");

                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();            
               String line = "";               
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }
                // Response from server after login process will be stored in response variable.                
                response = sb.toString();
                // You can perform UI operations here
                Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
                isr.close();
                reader.close();


            }
            catch(IOException e)
            {
                // Error
            }
                }

3 个答案:

答案 0 :(得分:1)

    public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

              InputStream is = httpResponse.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
String json = sb.toString();///HERE IS WHAT YOU NEED

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

答案 1 :(得分:0)

i am using for posts requests the followig code which works for me perfectly:
private String sendPostRequest(String restPath, String param1,String param2) {
        String response = "ERROR";
        try {
            data = URLEncoder.encode("param1Key", "UTF-8") + "="
                        + URLEncoder.encode(param1, "UTF-8");
                data += "&" + URLEncoder.encode("param2Key", "UTF-8") + "="
                        + URLEncoder.encode(param2, "UTF-8");



                        URL url = new URL(SERVER_ADRRESS + restPath);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            String answer = "";
            while ((line = rd.readLine()) != null) {

                Log.i("sendPostRequest, " + restPath + ":", line);
                answer += line;

            }
            wr.close();
            rd.close();
            response = answer;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            return response;
        }

        return response;
    }

我希望它有所帮助 干杯!

答案 2 :(得分:0)

使用asynctask

http://developer.android.com/reference/android/os/AsyncTask.html

在你的代码中使用它

       if (Build.VERSION.SDK_INT>= 10) {
        ThreadPolicy tp = ThreadPolicy.LAX;
        StrictMode.setThreadPolicy(tp);
        }

android不允许在主线程上进行网络操作&gt; API 9