首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >POST请求发送JSON数据Java HttpUrlConnection

POST请求发送JSON数据Java HttpUrlConnection
EN

Stack Overflow用户
提问于 2014-01-28 19:23:08
回答 5查看 344.3K关注 0票数 107

我已经开发了一个Java代码,可以使用URL和HttpUrlConnection将以下cURL转换为java代码。cURL为:

代码语言:javascript
运行
复制
curl -i 'http://url.com' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": { "passwordCredentials": {"username": "adm", "password": "pwd"},"tenantName":"adm"}}'

我已经写了这段代码,但它总是给HTTP代码400错误的请求。我找不到丢失的东西。

代码语言:javascript
运行
复制
String url="http://url.com";
URL object=new URL(url);

HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");

JSONObject cred   = new JSONObject();
JSONObject auth   = new JSONObject();
JSONObject parent = new JSONObject();

cred.put("username","adm");
cred.put("password", "pwd");

auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString());

parent.put("auth", auth.toString());

OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
wr.flush();

//display what returns the POST request

StringBuilder sb = new StringBuilder();  
int HttpResult = con.getResponseCode(); 
if (HttpResult == HttpURLConnection.HTTP_OK) {
    BufferedReader br = new BufferedReader(
            new InputStreamReader(con.getInputStream(), "utf-8"));
    String line = null;  
    while ((line = br.readLine()) != null) {  
        sb.append(line + "\n");  
    }
    br.close();
    System.out.println("" + sb.toString());  
} else {
    System.out.println(con.getResponseMessage());  
}  
EN

Stack Overflow用户

发布于 2021-09-25 09:53:02

这里是完整的代码和解决方案

PostJSONWithHttpURLConnection.java类

代码语言:javascript
运行
复制
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostJSONWithHttpURLConnection {
    String charset = "UTF-8";
    HttpURLConnection con;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder result;

    public JSONObject makeHttpRequest(String url,
                                      String paramsJSON) {
        try {
            urlObj = new URL(url);
            con = (HttpURLConnection) urlObj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");

            con.setDoOutput(true);
            con.setReadTimeout(60000);
            con.setConnectTimeout(60000);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = paramsJSON.getBytes(charset);
                os.write(input, 0, input.length);
            }

            int code = con.getResponseCode();
            Log.d("HTTP CODE", String.valueOf(code));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(con.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        con.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }
}

在doInBackground上使用代码(字符串...strArr)

代码语言:javascript
运行
复制
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String writeValueAsString = objectMapper.writeValueAsString(jSONObject);   
PostJSONWithHttpURLConnection jsonPOST = new PostJSONWithHttpURLConnection();
JSONObject json = jsonPOST.makeHttpRequest(SERVER_ADDRESS + "YOUR_API", writeValueAsString);

jSONObject是一个Json,如下所示:

代码语言:javascript
运行
复制
{
"Password":"PASSWORD",
"FullName":"Full Name",
"Username":"USER_NAME"
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21404252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档