0

Could anyone advise on why this code would not work for a HTTP Post with JSON? No response is received.

I am using Java in Android Studio - using the emulator on my laptop and want to access localhost on my laptop (so using 10.0.2.2). Then want to take the JSON response, set this as a string just to test I am getting a response.

    String jsonResponse = "No response received";

    try {
        //where write JSON with account details etc
        JSONObject json = new JSONObject();
        json.put("accountID", "test");

        URL url = new URL("http://10.0.2.2:8082/queryTransaction");
        HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
        httpcon.setDoOutput(true);
        httpcon.setRequestMethod("POST");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");

        OutputStreamWriter output = new OutputStreamWriter(httpcon.getOutputStream());
        output.write(json.toString());
        httpcon.connect();
        jsonResponse = httpcon.getResponseMessage();//json response from API


    }catch(Exception e){

    }

Edit: I get this error which I have now found... Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()

Chris
  • 45
  • 1
  • 1
  • 8
  • Does this answer your question? [Sending HTTP POST Request In Java](https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java) – Jochen Bedersdorfer Mar 27 '20 at 17:18

1 Answers1

0

so there are a few caveats with this. I got this working after making a few changes.

  1. Make sure to set the charset.
setRequestProperty("charset", "utf-8");
  1. Dont wrap the OutputStream, put it in a try-with-resources, and write the json as a byte array as utf-8 since that what we're accepting.
try (OutputStream output = httpcon.getOutputStream()) {
    output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}
  1. Make sure your Json object is correct. If you're going to use accountID make sure you're consuming it properly. Gson/Jackson for example won't be able to parse this as conventionally it would accept account_id or accountId. Use @JsonProperty if needed.
@JsonProperty("account_id")
private final String accountId;

Example Controller with Spring Boot

@RestController
public class TestPostController {

    public static class Account {

        @JsonProperty("account_id")
        private final String accountId;

        public Account(String accountId) {
            this.accountId = accountId;
        }

        public Account() {
            this(null);
        }

        public String getAccountId() {
            return accountId;
        }
    }
    @PostMapping(path = "/test-post", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<Account> response(@RequestBody Account account) {
        return ResponseEntity.ok(account);
    }

}
Jason
  • 5,154
  • 2
  • 12
  • 22