【问题标题】:easy way to do POST on HTTPURLConnection? [duplicate]在 HTTPURLConnection 上进行 POST 的简单方法? [复制]
【发布时间】:2015-04-10 03:40:31
【问题描述】:

在 Android 上的 AsyncTask 中的 HTTPURLCONNECTION 上进行 POST 的最简单方法是什么? 我只想在我的 php 文件上发布数据,然后返回一个 json 响应

【问题讨论】:

    标签: php android json


    【解决方案1】:

    你可以从我前几天给你的这个答案拼凑起来: How to get JSON object using HttpURLConnection instead of Volley?

    ...以及这里的答案:Java - sending HTTP parameters via POST method easily

    话虽如此,开始发送 POST 数据并获得 JSON 结果的最简单方法就是使用旧 API。

    这是一个工作示例:

    class CreateNewProduct extends AsyncTask<String, String, JSONObject> {
    
            InputStream is = null;
            JSONObject jObj = null;
            String json = "";
    
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(ShareNewMessage.this);
                pDialog.setMessage("Sharing Message...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
    
            /**
             * Creating product
             * */
            protected JSONObject doInBackground(String... args) {
    
                String message = inputMessage.getText().toString();
    
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", username));
                params.add(new BasicNameValuePair("message", message));
    
                Log.d("Share", "Sharing message, username: " + username + " message: " + message);
    
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url_create_message);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
    
                try {
                    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();
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e("Share", "Error converting InputStream result " + e.toString());
                }
    
                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("Share", "Error parsing JSON data " + e.toString());
                }
    
                try{
                    int success = jObj.getInt(TAG_SUCCESS);
    
                    if (success == 1) {
                        // successfully created product
    
                    } else {
                        // failed to create product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
                return jObj;
            }
    
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(JSONObject jObj) {
    
                //do something with jObj
    
                // dismiss the dialog once done
                pDialog.dismiss();
            }
    
        }
    

    【讨论】:

    • 你又一次帮助了我。谢谢你:)
    【解决方案2】:

    这是一个如何将图像上传到服务器的示例代码

    class ImageUploadTask extends AsyncTask <Void, Void, String>{
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(
                        getString(R.string.WebServiceURL)
                                + "/cfc/iphonewebservice.cfc?method=uploadPhoto");
    
                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
    
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                entity.addPart("photoId", new StringBody(getIntent()
                        .getStringExtra("photoId")));
                entity.addPart("returnformat", new StringBody("json"));
                entity.addPart("uploaded", new ByteArrayBody(data,
                        "myImage.jpg"));
                entity.addPart("photoCaption", new StringBody(caption.getText()
                        .toString()));
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));
    
                String sResponse = reader.readLine();
                return sResponse;
            } catch (Exception e) {
                if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(),
                        getString(R.string.exception_message),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }
    
            // (null);
        }
    

    有关这方面的完整教程,请访问this

    在上面的代码中,你可以发送任何你想发送的表单数据,只需添加

    entity.addPart("value", new StringBody(key));
    

    【讨论】:

      【解决方案3】:

      试试这个

          public class parseProduct extends AsyncTask<Void, Void, Void> {
      String jsonResponse;
              @Override
              protected void onPreExecute() {
      
                  super.onPreExecute();
              }
      
              @Override
              protected Void doInBackground(Void... params) {
                  JSONObject object = new JSONObject();
                  try {
                      object.put("registeruserid", userId); // you can pass data which you want to pass from POST
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
                  try {
                      jsonResponse=getResponseStringFromURL2(URL,object.toString());
      
                  } catch (ClientProtocolException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
                  return null;
              }
      
              @Override
              protected void onPostExecute(Void resul) {
                  super.onPostExecute(resul);
      
      
              }
      
          }
      

      功能如下:

      public String getResponseStringFromURL2(String url, String json)
                  throws ClientProtocolException, IOException {
              StringBuilder result = new StringBuilder();
              HttpParams httpParameters = new BasicHttpParams();
              int timeoutConnection = 30000;
              HttpConnectionParams.setConnectionTimeout(httpParameters,
                      timeoutConnection);
              int timeoutSocket = 30000;
              HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
              DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
              HttpPost request = new HttpPost(url);
              if (json != null) {
                  StringEntity se = new StringEntity(json);
                  request.setEntity(se);
              }
      
              request.setHeader("Accept", "application/json");
              request.setHeader("Content-type", "application/json");
              Log.d("request: ", ":" + request.getRequestLine());
              HttpResponse response = null;
              response = httpClient.execute(request);
              if (response == null)
                  return null;
      
              InputStream input = null;
      
              input = new BufferedInputStream(response.getEntity().getContent());
      
              byte data[] = new byte[40000];
      
              int currentByteReadCount = 0;
      
              /** read response from inpus stream */
      
              while ((currentByteReadCount = input.read(data)) != -1) {
                  String readData = new String(data, 0, currentByteReadCount);
                  result.append(readData);
              }
      
              input.close();
      
              return result.toString();
      
          }
      

      【讨论】:

        猜你喜欢
        • 2014-08-05
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 2014-01-30
        • 1970-01-01
        相关资源
        最近更新 更多