【问题标题】:I tried from POSTMAN API working fine but not from my Java code?我尝试从 POSTMAN API 工作正常但不是从我的 Java 代码?
【发布时间】:2017-07-07 23:12:13
【问题描述】:

请我已经解决了来自 stackoverflow 的所有问题,但这些问题不适用于我的问题。

请查看来自POSTMAN 的图像请求工作正常。

但是当我尝试使用android 代码时,它不起作用。 我的示例 Android 代码在这里。

@Override
        protected String doInBackground(Void... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                URL url = new URL("sample url");

                String postData = "key1=valu1&key2=valu2";

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(55000 /* milliseconds */);
                conn.setConnectTimeout(55000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os));
                writer.write(postData);

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(
                            new InputStreamReader(
                                    conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {
                        Log.e("response ",line);
                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            } catch (Exception e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {

                    }
                }
            }
        }

以上java代码返回405错误代码。我也尝试过OkHttp。 请帮忙。

【问题讨论】:

    标签: java android okhttp


    【解决方案1】:

    在 URL 末尾添加“/”会导致重定向发生,因为您的服务器喜欢以“/”结尾的 URL。您的服务器将您重定向到的 URL 完全支持 POST,但是当客户端根据您的 setRedirecting() 调用运行时,客户端正在执行 GET 请求(cURL 使用 -L 开关执行相同的操作)解决方法是要么放URL 末尾的“/”,或者自己从响应中获取 Location 标头,然后手动发起另一个 POST 请求。

    这可以在wireshark中观察到。您可以通过尝试使用浏览器对附加斜杠的 URL 执行 GET 请求来测试该理论。这将导致浏览器收到 405。这是 Android 的固定代码,此代码使用在 URL 上附加“/”的简单修复(未准备好生产):

    阅读更多来自here.

    如果这有帮助,请告诉我:)

    另外,尝试使用这段代码:

    public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://your URL");
    
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    } 
    

    【讨论】:

    • 我在提出问题之前尝试过,但对我不起作用
    • 您是否尝试过使用其他网址?
    • 好吧,你的网址有问题
    • 所以另一个 URL 可以正常使用您的代码,而这个 URL 会产生问题,对吗?您是否尝试调整标题?
    • 我需要设置任何特殊的标题吗?喜欢内容类型
    【解决方案2】:

    您的 API 调用正在接收 GET 参数中的数据。所以数据应该与下面给出的 url 一起发送

                String postData = Uri.encode("key1=valu1&key2=valu2");
                URL url = new URL("sample url"+"?+postData);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2021-03-28
      • 2018-03-30
      • 2022-06-13
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多