【问题标题】:Send "PUT" request in Android to rest api在Android中发送“PUT”请求到rest api
【发布时间】:2014-11-05 02:46:16
【问题描述】:

我有一个 android 应用程序,它可以咨询并插入到 web 服务中。 这一切都是通过 apache HTTPClient 和 JSON 实现的。

例如,我将一个新用户插入到数据库中。

HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("name", name);
            jsonObject2.put("number", num);
         // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
        // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
        // 6. set httpPost Entity
            httpPost.setEntity(se);
        // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

所有完美创建,现在我想使用我在其余 api 中创建的方法,方法 PUT 覆盖例如 ID 为 5 的用户的名称如果我想做一个 get 输入我的 url + / ID并获取特定用户。到“PUT”我这样做但不起作用。

 @Override
    protected String doInBackground(String... params) {
        InputStream inputStream = null;
        String result = ""; 

        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL

            HttpPut httpPut = new    
            HttpPut("http://000.000.0.000:0000/xxxxxx/webresources/net.xxxxx.users/5");
            String json = "";
            //              // 3. build jsonObject
            //              JSONObject jsonObject2 = new JSONObject();
            //              jsonObject2.put("idGuarderias", idG);
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name",newName);
            //      jsonObject.put("guarderiasIdGuarderias",jsonObject2);
            json = jsonObject.toString();
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPut.setEntity(se);
            // 7. Set some headers to inform server about the type of the content   
            httpPut.addHeader("Accept", "application/json");
            httpPut.addHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPut);

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

我应该做哪些改变?

【问题讨论】:

  • 不,只是不要在 bd 中输入任何内容...
  • 也不例外?奇怪,是不是正确的网址?
  • 您可以访问 REST 服务日志吗?有两种选择,一是您没有发送数据,二是服务出现问题。

标签: android json rest androidhttpclient


【解决方案1】:

这是我的代码。

在gradle中添加依赖

编译'com.squareup.okhttp:okhttp:2.6.0'

HttpUtils.class

public class HttpUtils {
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    public static OkHttpClient client = new OkHttpClient();

    /**
     * function for get url of webservice
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String getRun(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        client.setConnectTimeout(90, TimeUnit.SECONDS);
        client.setReadTimeout(90, TimeUnit.SECONDS);
        client.setWriteTimeout(90, TimeUnit.SECONDS);
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * function for post url of webservice
     *
     * @param type
     * @param formBody
     * @return
     * @throws IOException
     */

    public static String postRun(String type, RequestBody formBody) throws IOException {

        Response response = null;

        Request request = new Request.Builder()
                .url(type)
                .post(formBody)
                .build();
        client.setConnectTimeout(90, TimeUnit.SECONDS);
        client.setReadTimeout(90, TimeUnit.SECONDS);
        client.setWriteTimeout(90, TimeUnit.SECONDS);
        response = client.newCall(request).execute();
        return response.body().string();
    }

}

Registration.class

    public class Registration extends AppCompatActivity {

    private String mStrSocialLoginResponse;
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.registration); 
            new MyAsyncTask().execute();
        }

        public class MyAsyncTask extends AsyncTask<Void, Void, Void> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                }

                @Override
                protected Void doInBackground(Void... params) {

                    try {
                        RequestBody formBody = new FormEncodingBuilder()
                                .add("user_id", "1")
                                .build();

                        mStrSocialLoginResponse = HttpUtils.postRun("your url", formBody);
                        if (mStrSocialLoginResponse != null) {
                            try {
                                JSONObject jsonObjectLogin = new JSONObject(mStrSocialLoginResponse);
                                if (jsonObjectLogin.has("code")) {
                                    mCode = jsonObjectLogin.getInt("code");
                                    if (mCode == 1) {
                                        if (jsonObjectLogin.has("image_path")) {
                                            strImagePath = jsonObjectLogin.getString("image_path");
                                        }
                                        if (jsonObjectLogin.has("data")) {
                                            JSONArray jsonArray = jsonObjectLogin.getJSONArray("data");
                                            for (int i = 0; i < jsonArray.length(); i++) {
                                                modelSongs = new ModelSongs();
                                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                                if (jsonObj.has("id")) {
                                                    strSongId = jsonObj.getString("id");
                                                    modelSongs.setId(strSongId);
                                                    Log.e(TAG, "SongId " + modelSongs.getId());
                                                }
                                                if (jsonObj.has("song")) {
                                                    strSongs = jsonObj.getString("song");
                                                    modelSongs.setSong(strAudioPath + strSongs);
                                                    Log.i("GetSOng", "++" + modelSongs.getSong());
                                                }
                                                if (jsonObj.has("image")) {
                                                    strImage = jsonObj.getString("image");
                                                    modelSongs.setImage(strImagePath + strImage);
                                                }

                                                }
                                               mArrayListSongs.add(modelSongs);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }//if close

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                }
            }
}

希望这会对你有所帮助:-)

此链接也将有助于解决问题json parsing from url

【讨论】:

    【解决方案2】:

    希望这对某人有所帮助: 注意这里authToken是可选的

    public JSONObject makePutRequest(String path, String params, String authToken) {
    
        try {
            //instantiates httpclient to make request
            @SuppressWarnings("deprecation")
            DefaultHttpClient httpclient = new DefaultHttpClient();
    
            //url with the post data
            @SuppressWarnings("deprecation")
            HttpPut httpost = new HttpPut(path);
            if (authToken != null) {
                httpost.setHeader("X-Auth-Token", authToken);
            }
            //passes the results to a string builder/entity
            @SuppressWarnings("deprecation")
            StringEntity se = new StringEntity(params.toString());
    
            //sets the post request as the resulting string
            httpost.setEntity(se);
            //sets a request header so the page receving the request
            //will know what to do with it
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");
            response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    
            if (is != null) {
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            }
            jsonObject = new JSONObject(result);
            Log.i("Response", "" + jsonObject.toString());
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    
    }
    

    【讨论】:

      【解决方案3】:

      试试这个代码: 您可以在 jsonObject 对象中添加参数

      JSONObject jsonObject = new JSONObject();
      jsonObject.put("name",newName);
      try {
          HttpResponse response;
          HttpParams httpParameters = new BasicHttpParams();
          HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
          HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT);
          HttpClient httpClient = new DefaultHttpClient(httpParameters);
          HttpPut putConnection = new HttpPut(url);
          putConnection.setHeader("json", jsonObject.toString());
          StringEntity se = new StringEntity(jsonObject.toString(), "UTF-8");
          se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                  "application/json"));
          putConnection.setEntity(se);
          try {
              response = httpClient.execute(putConnection);
              String JSONString = EntityUtils.toString(response.getEntity(),
                      "UTF-8");
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
      

      【讨论】:

      • 谢谢,但我在哪里写例如这个 - ("name",newName);
      • @egh 你想添加什么?基本认证?还是加 JSON 参数?
      • JSON 参数。我想覆盖一个参数,例如在特定的用户 ID 中进行更改,
      【解决方案4】:

      我用下面的代码解决了我的问题,感谢回复。

      @Override
          protected String doInBackground(String... params) {
              InputStream inputStream = null;
              String result = ""; 
      
              try {
                  // 1. create HttpClient
                  HttpClient httpclient = new DefaultHttpClient();
                  // 2. make POST request to the given URL
                  HttpPut httpPUT = new    
                         HttpPut("http://xxx.xx.x.xxx:xxxx/xxxxxxxy/webresources/net.xxxxxx.users/3");
                  String json = "";
                  // 3. build jsonObject
                  JSONObject jsonObject = new JSONObject();
                  jsonObject.put("idUser","3");
                  jsonObject.put("name","Mark");
                  jsonObject.put("pass","1234");
                  jsonObject.put("rol","554");
                  jsonObject.put("usuario","mark");
      
      
      
      
                  // 4. convert JSONObject to JSON to String
                  json = jsonObject.toString();
      
                  // 5. set json to StringEntity
                  StringEntity se = new StringEntity(json);
                  // 6. set httpPost Entity
                  httpPUT.setEntity(se);
                  // 7. Set some headers to inform server about the type of the content   
                  httpPUT.setHeader("Accept", "application/json");
                  httpPUT.setHeader("Content-type", "application/json");
                  // 8. Execute POST request to the given URL
                  HttpResponse httpResponse = httpclient.execute(httpPUT);
                  // 9. receive response as inputStream
                  //                  inputStream = httpResponse.getEntity().getContent();
                  //                  // 10. convert inputstream to string
                  //                  if(inputStream != null)
                  //                      result = convertInputStreamToString(inputStream);
                  //                  else
                  //                      result = "Did not work!";
              } catch (Exception e) {
                  Log.d("InputStream", e.getLocalizedMessage());
              }
      
              return "EXITO!";
          }
      

      他们应该将id放在url中,并覆盖包括id在内的所有参数

      【讨论】:

        【解决方案5】:

        也许你可以试试这个:

        @Override
        protected String doInBackground(String... params) {
            InputStream inputStream = null;
            String result = ""; 
        
            try {
                // 1. create HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // 2. make POST request to the given URL
        
                HttpPut httpPut = new    
                HttpPut("http://000.000.0.000:0000/xxxxxx/webresources/net.xxxxx.users/5");
                String json = "";
                //              // 3. build jsonObject
                //              JSONObject jsonObject2 = new JSONObject();
                //              jsonObject2.put("idGuarderias", idG);
                // 3. build jsonObject
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name",newName);
                //      jsonObject.put("guarderiasIdGuarderias",jsonObject2);
                json = jsonObject.toString();
                StringEntity se = new StringEntity(json);
                // 6. set httpPost Entity
                httpPut.setEntity(se);
                // 7. Set some headers to inform server about the type of the content   
                httpPut.addHeader("Accept", "application/json");
                httpPut.addHeader("Content-type", "application/json");
                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPut);
        
        
                //Try to add this
               inputStream = httpResponse.getEntity().getContent();
        
                if(inputStream != null)
                    result = convertInputStreamToString(inputStream);
                else
                    result = "Did not work!";
        
            } catch (Exception e) {
                //Log.d("InputStream", e.getLocalizedMessage());
            }
            return result;
        }
        

        【讨论】:

        • 谢谢,但这不会覆盖我的 bd 中 ID 为 5 的用户的值“名称”。
        猜你喜欢
        • 1970-01-01
        • 2021-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-31
        • 2019-03-29
        • 1970-01-01
        相关资源
        最近更新 更多