我尝试从POSTMAN API工作正常而不是我的Java代码?

时间:2017-02-18 11:39:41

标签: java android okhttp

请问我是否已经完成了stackoverflow的所有问题,但这些问题并不适用于我的问题。

enter image description here 请从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。 请帮忙。

2 个答案:

答案 0 :(得分:1)

提出' /'在URL的末尾会导致重定向发生,因为您的服务器喜欢以' /'结尾的网址。服务器重定向到您的URL完全支持POST,但客户端在根据您的setRedirecting()调用行为时执行GET请求(cURL与-L开关完全相同)修复是放置a' /'在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
}
} 

答案 1 :(得分:0)

您的API调用正在重新获取GET参数中的数据。因此,数据应与url一起发送,如下所示

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