java 使用 POST 方法发送 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7316501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:31:05  来源:igfitidea点击:

sending JSON object using POST Methods

javaandroidtwitter-oauthoauth-2.0

提问by ritesh Mehandiratta

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent in=getIntent();

        Uri uri=in.getData();

            // l.setText(uri.toString());
             String p=uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
             CreateFolderActivity.m_provider.setOAuth10a(true);
             try {
                CreateFolderActivity.m_provider.retrieveAccessToken(p);
            } catch (OAuthMessageSignerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthNotAuthorizedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             URL url = null;
                try {
                    url = new URL("http://api.mendeley.com/oapi/library/folders?consumer_key=" + CreateFolderActivity.m_consumer_key);


                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                HttpURLConnection hc=null;
                try {
                    hc=(HttpURLConnection)url.openConnection();
                    try {CreateFolderActivity.m_consumer.sign(hc);

                        hc.setRequestMethod("POST");
                        hc.setDoInput(true);
                        hc.setDoOutput(true);
                        hc.setUseCaches(false); 

                        hc.setRequestProperty("Content-type","text/json; charset=utf-8"); 
                        OutputStreamWriter wr = new OutputStreamWriter(hc.getOutputStream());
                        wr.write("folder = {'name' : 'Test creation folder'}");

                        wr.flush();

                        // Get the response
                     /*   BufferedReader rd = new BufferedReader(new InputStreamReader(hc.getInputStream()));
                        String strResponse = null;
                        for (String strLine = ""; strLine != null; strLine = rd.readLine()) 
                            strResponse += strLine ;*/
                        Log.i("HelloWorld",hc.getResponseMessage()+"    "+hc.getResponseCode());
                    } catch (OAuthMessageSignerException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


  }
  }`

hi i am trying to send a json Object using post method here above is code but i am getting internal server error 500.i read its appear when u send some unexpected data.Actually its an OAuth implementation and i have to add a folder in the user account.and i retrieve access token successfully.please suggest what is wrong in code

嗨,我正在尝试使用上面的 post 方法发送一个 json 对象,这里是代码,但我收到内部服务器错误 500。当你发送一些意外数据时,我读取了它的出现。实际上它是一个 OAuth 实现,我必须在用户帐户。我成功检索访问令牌。请建议代码中有什么问题

回答by Sahil Muthoo

  • "folder = {'name' : 'Test creation folder'}"is invalid JSON. JSON Stringsmust be enclosed with double-quotes ("). I think you meant this:

    {
        "folder": {
            "name": "Test creation folder"
        }
    }
    
    1. Refer to the JSON specification.
    2. Validate your JSON.
    3. Pretty print your JSON.
  • The correct JSON mime type is application/json.

  • Don't build your JSON by hand. Use the org.jsonpackage. Start by looking at JSONObjectand JSONArray.

  • "folder = {'name' : 'Test creation folder'}"是无效的 JSON。JSONStrings必须用双引号 ( ")括起来。我想你的意思是:

    {
        "folder": {
            "name": "Test creation folder"
        }
    }
    
    1. 请参阅 JSON 规范
    2. 验证您的 JSON
    3. 漂亮地打印你的 JSON
  • 正确的 JSON mime 类型是application/json.

  • 不要手动构建 JSON。使用org.json包。从查看JSONObject和开始JSONArray

Example:

例子:

hc.setRequestProperty("content-type","application/json; charset=utf-8"); 
OutputStreamWriter wr = new OutputStreamWriter(hc.getOutputStream());
JSONObject data = new JSONObject().put("folder",
                  new JSONObject().put("name", "test creation folder"));
wr.write(data.toString());