POST 请求发送 JSON 数据 JavaHttpUrlConnection

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

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坏请求。我无法找到什么是缺失的。

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());
}
361530 次浏览

Your JSON is not correct. Instead of

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()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()


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

write

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);
parent.put("auth", auth);


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

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");


// ...


OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();

You can use this code for connect and request using http and json

try {
         

URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
+ "&key="+key
+ "&access_token=" + access_token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
 

String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
 

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
 

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
 

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
 

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
 

conn.disconnect();
 

} catch (MalformedURLException e) {
 

e.printStackTrace();
 

} catch (IOException e) {
 

e.printStackTrace();
 

}

the correct answer is good , but

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

not work for me , instead of it , use :

byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);
private JSONObject uploadToServer() throws IOException, JSONException {
String query = "https://example.com";
String json = "{\"key\":1}";


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


OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();


// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(result);




in.close();
conn.disconnect();


return jsonObject;
}

I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.

Below code worked fine for POST but was giving BAD Request for PUT:

conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);

After making below changes worked fine for both POST and PUT

conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));

Here is full Code and Solutions

PostJSONWithHttpURLConnection.java Class

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;
}
}

Use of Code on doInBackground(String... strArr)

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 is a Json Like:

{
"Password":"PASSWORD",
"FullName":"Full Name",
"Username":"USER_NAME"
}