当前位置: 首页 > 知识库问答 >
问题:

使用HttpURLConnection的Android POST请求

晋承嗣
2023-03-14

我试图使用HttpURLConnection执行post请求,但不知道如何正确执行。

我可以使用以下代码成功地使用Android AsyncHttp客户端执行请求:

AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Content-type", "application/json");
httpClient.setUserAgent("GYUserAgentAndroid");
String jsonParamsString = "{\"key\":\"value\"}";
RequestParams requestParams = new RequestParams("request", jsonParamsString);
httpClient.post("<server url>", requestParams, jsonHttpResponseHandler);

可以在台式机上使用curl执行相同的请求:

curl -A "GYUserAgentAndroid" -d 'request={"key":"value"}' '<server url>'

这两种方法都给了我来自服务器的预期响应。

现在我想使用HttpURLConntions执行相同的请求。问题是我不知道如何正确地执行它。我尝试过这样的事情:

URL url = new URL("<server url>");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("User-Agent", "GYUserAgentAndroid");
httpUrlConnection.setRequestProperty("Content-Type", "application/json");
httpUrlConnection.setUseCaches (false);

DataOutputStream outputStream = new DataOutputStream(httpUrlConnection.getOutputStream());

// what should I write here to output stream to post params to server ?

outputStream.flush();
outputStream.close();

// get response
InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
    stringBuilder.append(line);
}
responseStreamReader.close();

String response = stringBuilder.toString();
JSONObject jsonResponse = new JSONObject(response);
// the response is not I'm expecting

return jsonResponse;

如何正确地将与使用AsyncHttpClient和curl的工作示例中相同的数据写入HttpURLConnection输出流?

先谢谢你。

共有3个答案

彭俊智
2023-03-14

这里您有一个使用HttpUrlConntions的请求,您缺少的只是从服务器读取值。

try {
    JSONObject job = new JSONObject(log);
    String param1 = job.getString("AuditScheduleDetailID");
    String param2 = job.getString("AuditAnswerId");
    String param3 = job.getString("LocalFindingID");
    String param4 = job.getString("LocalMediaID");
    String param5 = job.getString("Files");
    String param6 = job.getString("ExtFiles");
    Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
            "pertama");

    URL url = new URL("myurl");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    conn.setRequestProperty("Accept", "application/json");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("AuditScheduleDetailID", param1);
    jsonParam.put("AuditAnswerId", param2);
    jsonParam.put("LocalFindingID", param3);
    jsonParam.put("LocalMediaID", param4);
    jsonParam.put("Files", param5);
    jsonParam.put("ExtFiles", param6);

    Log.i("JSON", jsonParam.toString());
    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
    //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
    os.writeBytes(jsonParam.toString());

    os.flush();
    os.close();
    InputStream is = null;

    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            is = conn.getInputStream();// is is inputstream
        } else {
            is = conn.getErrorStream();
        }


        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        String response = sb.toString();
        //HERE YOU HAVE THE VALUE FROM THE SERVER
        Log.d("Your Data", response);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }


    conn.disconnect();
} catch (JSONException | IOException e) {
    e.printStackTrace();
} 
郭云
2023-03-14

您可以使用以下内容来发布参数

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
寇靖
2023-03-14
    public String getJson(String url,JSONObject params){
    try {
        URL _url = new URL(url);
        HttpURLConnection urlConn =(HttpURLConnection)_url.openConnection();
        urlConn.setRequestMethod(POSTMETHOD);
        urlConn.setRequestProperty("Content-Type", "applicaiton/json; charset=utf-8");
        urlConn.setRequestProperty("Accept", "applicaiton/json");
        urlConn.setDoOutput(true);
        urlConn.connect();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        writer.write(params.toString());
        writer.flush();
        writer.close();

        if(urlConn.getResponseCode() == HttpURLConnection.HTTP_OK){
            is = urlConn.getInputStream();// is is inputstream
        } else {
            is = urlConn.getErrorStream();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
        Log.e("JSON", response);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return response ;

}
 类似资料:
  • 我正在尝试进行http补丁请求,但我总是得到404错误,所以可能是我的连接设置不正确: 我收到404错误,未找到。当使用Postman执行相同的请求时,这是有效的…谢谢你的帮助。

  • 我正在尝试使用HttpUrlConnection发送帖子。一切看起来都很好,但它保持返回400,就好像参数不是在DataOutputStream中发送的,或者是以错误的方式发送的。 这是返回的内容: 这很奇怪,因为这个卷曲正常工作: 它会返回我想要的访问令牌

  • 我被夹在中间。我想实现一个POST方法,使用HttpUrlConnection向服务器发送注册用户的电子邮件、名称和密码。以下是我的代码: 我不知道我在哪里犯了错误。我收到以下回复 空格后的“0”是超文本传输协议响应代码返回的响应代码。当我在浏览器中尝试时,我的网址是正确的。我不知道我在哪里犯了错误;是我的服务器故障还是我的代码有错误,因为我不认为我的代码有任何交互处理。 我是Android开发的

  • 如何使用< code>HttpURLConnection设置HTTP请求方法MOVE? 使用< code>HttpURLConnection或依赖于该类的库,代码将引发异常< code >,其原因是:Java . net . protocol exception:Invalid HTTP method:MOVE 。所以我猜Java平台不支持< code>MOVE方法。 是否有针对此问题/限制的补丁

  • 问题内容: 使用HttpURLConnection时,如果我们不“获取”并使用它,是否需要关闭InputStream? 即安全吗? 其次, 在完全读取所有内容之前 关闭InputStream是否安全? 是否存在使基础套接字处于ESTABLISHED或CLOSE_WAIT状态的风险? 问题答案: 在读取所有内容之前关闭InputStream是否安全? 您需要先关闭输入流中的所有数据,然后再关闭它,以

  • 我试图使用android HttpUrlConnection进行POST请求。首先,我从这里使用GET请求的示例: http://developer.android.com/training/basics/network-ops/connecting.html#http-客户 它工作得非常好(例如,我得到了google.com页面)。然后我做了一些更改以发出POST请求:更改POST上的请求方法: