【问题标题】:How to get response after using POST method in Android在 Android 中使用 POST 方法后如何获得响应
【发布时间】:2026-02-11 21:40:02
【问题描述】:

网址是:http://localhost 方法类型:post 标头:内容类型:应用程序/json,解码:2 数据:xx

我们如何在 android 中实现这一点??我如何得到响应? 我看到 Httpclient 已被弃用

任何帮助将不胜感激

【问题讨论】:

标签: android androidhttpclient


【解决方案1】:

您可以使用 Retrofit 库,因为 Retrofit 比其他方法更快、更容易地从 HTTP 请求加载响应。 访问,https://square.github.io/retrofit/

例如,这里给出的示例 Json 对象,

{
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}  

代码:

public interface APIService {

    @POST("/posts")
    @FormUrlEncoded
    Call<Post> savePost(@Field("title") String title,
                    @Field("body") String body,
                    @Field("userId") long userId);
}

【讨论】:

    【解决方案2】:

    尝试使用 HttpUrlConnection

    String Url, query;
    
        InputStream inputStream;
        HttpURLConnection urlConnection;
        byte[] outputBytes;
        String ResponseData;
        Context context;
    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.setRequestProperty("Content-Type", "application/json");
                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();
    
                }
    
    
        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 对象
    • 它将以json字符串形式给出响应,您可以将其转换为jsonObject
    • 它说 Unhandled Exception:java.io.IOException in url.openconnection
    • 检查我的编辑我添加了 try catch 代码来处理异常
    【解决方案3】:
     URL url = new URL("http://yoururl.com");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("firstParam", paramValue1));
    params.add(new BasicNameValuePair("secondParam", paramValue2));
    params.add(new BasicNameValuePair("thirdParam", paramValue3));
    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();
    conn.connect();
    

    .................................................. ....................

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
    
        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");
    
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
    
        return result.toString();
    }
    

    【讨论】:

    • 非常感谢,这有帮助,但是我如何向其中添加内容类型??,我有一个 json 对象
    • getQuery 将返回包含您的 JSON 的字符串,之后您可以提取它。如果代码对您有帮助,那么您可以标记为答案,谢谢
    【解决方案4】:

    如果您不想使用库,可以使用 HttpURLConnection,否则您也可以使用 Volley 进行网络调用,因为 volley 可以更轻松地管理网络调用! 谢谢!

    【讨论】:

    • 我能举个例子吗,我是android新手
    • numetriclabz.com/… 用于 HttpURLConnection
    • 但我建议你先使用 HttpURLConnection 然后你可以尝试 volley 和其他 lib 如果我的回答对你有帮助请接受我的回答