POST заявка изпраща JSON данни Java HttpUrlConnection

Разработих Java код, който преобразува следния cURL в Java код, използвайки URL и HttpUrlConnection. 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());  
}  

person user3244172    schedule 28.01.2014    source източник
comment
Хубава илюстрация за многословност на java.   -  person yurin    schedule 30.03.2016


Отговори (4)


Вашият JSON не е правилен. Вместо

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());

пишете

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());

Така че JSONObject.toString() трябва да се извика само веднъж за външния обект.

Друго нещо (най-вероятно не е вашият проблем, но бих искал да го спомена):

За да сте сигурни, че няма да срещнете проблеми с кодирането, трябва да посочите кодирането, ако не е 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();
person hgoebl    schedule 28.01.2014
comment
В моя случай настройката на типа съдържание на свойството на заявката беше от решаващо значение: con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); - person Morey; 31.10.2016
comment
нищо не ми работи. Изпращам входа, но от страна на API получавам празен. - person Adarsh Singh; 28.05.2020

Можете да използвате този код за свързване и заявка чрез http и 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();
 
     }
person Burak Durmuş    schedule 02.12.2014

правилният отговор е добър, ноно

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

не работи за мен, вместо него, използвайте:

byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);
person Adnan Abdollah Zaki    schedule 15.09.2015
comment
не работи за вас, защото сте забравили да затворите OutputStreamWriter - person Sujal Mandal; 28.03.2019

Имах подобен проблем, получавах 400, лоша заявка само с PUT, където като POST заявка беше напълно добре.

Кодът по-долу работи добре за POST, но дава ЛОША заявка за PUT:

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

След извършване на промените по-долу работеха добре както за POST, така и за PUT

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