【问题标题】:HttpUrlConnection POST request not working....How to solve this?HttpUrlConnection POST 请求不起作用....如何解决这个问题?
【发布时间】:2017-04-18 10:24:44
【问题描述】:

HttpUrlConnection POST 请求不起作用。告诉我是否有任何其他方式可以在 android 中发出 POST 请求。告诉我是否有任何其他方式可以在 android 中发出 POST 请求。告诉我是否有任何其他方式可以在 android 中发出 POST 请求。

 public final String apiCall(String pUrl) {
    if( ! isInternetAvailable() )
        return "NO_INTERNET";

    try {
        URL lUrl = new URL(pUrl.replace(" ", "%20"));
        Log.i("url", String.valueOf(lUrl));

       String url = pUrl;

        Log.i("dom", url.substring(0, (url.indexOf('?') - 1)));
        Log.i("para", url.substring((url.indexOf('?') + 1), url.length()) );

        URL obj = new URL(url.substring(0,(url.indexOf('?')-1)));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "GYUserAgentAndroid");
        con.setRequestProperty("Content-Type", "application/json");

        String urlParameters = url.substring((url.indexOf('?')+1), url.length());
        Log.i("urlParameters", urlParameters.toString());

        // Send post request
        con.setDoInput(true); // true if we want to read server's response
        con.setDoOutput(true); // false indicates this is a GET request
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


        Log.i("res",response.toString());
        return response.toString();

    }catch (Exception e) {
        Log.i("secondEx",e.toString());
        return "ERROR";
    }

}

【问题讨论】:

  • 我建议您使用 Retrofit - 它是适用于 Android 和 Java 的类型安全 HTTP 客户端。在这里你可以研究这个square.github.io/retrofit

标签: android


【解决方案1】:

另一种执行请求的方式是Retrofit

你可以找到一个很好的教程here

【讨论】:

    【解决方案2】:

    试试这个

    InputStream inputStream; 
    HttpURLConnection urlConnection; 
    byte[] outputBytes;
    
    public class WebServiceAsyncTask extends AsyncTask<Void, Void, String> {
    
        @Override
        protected String doInBackground(Void... params) {
    
            try {
                URL url = new URL(Url);
                urlConnection = (HttpURLConnection) url.openConnection();
                outputBytes = query.getBytes("UTF-8");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlConnection.setConnectTimeout(15000);
                urlConnection.connect();
    
                OutputStream os = urlConnection.getOutputStream();
                os.write(outputBytes);
                os.flush();
                os.close();
    
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                ResponseData = convertStreamToString(inputStream);
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
    
            }
            return ResponseData;
        }
    
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
    
    
        }
    
        public String convertStreamToString(InputStream is) {
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
    
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append((line + "\n"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    }
    

    像这样以 json 字符串格式传递参数

    JSONObject() params = new JSONObject();
    params.put("key","your parameter");
    params.put("key","your parameter");
    
    query=params.toString();
    

    查看this链接以供参考

    【讨论】:

    • 输出字节数?查询?
    • query 是您发送到 post api 的参数。它是json字符串格式
    • 是否有必要创建 JSONObject ,因为我已经直接将参数字符串分配给字符串变量,例如这样 String urlParameters = url.substring((url.indexOf('?')+1), url.长度());和 .urlParameters.getBytes("UTF-8");
    • 嗯,这取决于您的要求..如果它需要 json 格式的参数,那么您必须使用它,否则您也可以发送它..试试看
    猜你喜欢
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多