Permintaan POST mengirim data json java HttpUrlConnection

98

Saya telah mengembangkan kode java yang mengubah cURL berikut ke kode java menggunakan URL dan HttpUrlConnection. ikalnya adalah:

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"}}'

Saya telah menulis kode ini tetapi selalu memberikan kode HTTP 400 permintaan buruk. Saya tidak dapat menemukan apa yang hilang.

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());  
}  
pengguna3244172
sumber
4
Ilustrasi yang bagus untuk verbositas java.
yurin

Jawaban:

163

JSON Anda salah. Dari pada

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

menulis

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

Jadi, JSONObject.toString () harus dipanggil hanya sekali untuk objek luar.

Hal lain (kemungkinan besar bukan masalah Anda, tetapi saya ingin menyebutkannya):

Untuk memastikan tidak mengalami masalah encoding, Anda harus menentukan encoding, jika tidak 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();
hgoebl
sumber
7
Dalam kasus saya, menyetel jenis konten properti permintaan sangat penting:con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Morey
tidak ada yang berhasil untuk saya. Saya mengirim input tetapi di sisi API saya menerima kosong.
Adarsh ​​Singh
36
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;
    }
NickUnuchek
sumber
15

Anda dapat menggunakan kode ini untuk menghubungkan dan meminta menggunakan http dan json

try {

        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo"
                + "&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();

     }
Burak Durmuş
sumber
6

jawaban yang benar itu bagus, tapi

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

tidak berfungsi untuk saya , alih-alih, gunakan :

byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);
Adnan Abdollah Zaki
sumber
itu tidak berhasil untuk Anda karena Anda lupa menutup OutputStreamWriter
Sujal Mandal
2

Saya memiliki masalah serupa, saya mendapatkan 400, Permintaan Buruk hanya dengan PUT, sedangkan permintaan POST baik-baik saja.

Kode di bawah ini berfungsi dengan baik untuk POST tetapi memberikan Permintaan BURUK untuk PUT:

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

Setelah membuat perubahan di bawah ini berfungsi dengan baik untuk POST dan PUT

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