简体   繁体   中英

Java: Preview HttpPost Request

I am trying to send JSON formatted data to a server using Java. The information is getting to the server, but the server is responding with a "Bad Request".

    HttpPost httpost = new HttpPost(path);

    StringEntity se = new StringEntity(JSONRequest);

    //sets the post request as the resulting string
    httpost.setEntity(se);

    //sets a request header so the page receving the request will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json;charset=utf8");
    HttpResponse response = httpclient.execute(httpost);

That is the basic setup of my request. Here is the JSONData:

    {"clientApplicationDto":{"AuthenticationToken":"","BrandId":12,"MobileDeviceApplicationId":0},"mobileDeviceInfo":{"CarrierName":"MTN-SA","OsVersion":"2.2.2","ClientApplicationVersion":"TEST","DeviceManufacturer":"HTC","DeviceName":"HTC Desire","DeviceUniqueId":"1e9766fa2ef4c53a","OsName":"8","ClientApplicationTypeId":3}}

If this looks right to you lot, I'll start spamming the admins, but for now, I need to know if I am missing something.

I found the issue... The server is extremely sensitive to the content type header and the content format

    httpost.setHeader("Content-type", "application/json;charset=utf8");

Needed to be changed to

    httpost.setHeader("Content-type", "application/json; charset=utf-8");

and StringEntity se = new StringEntity(JSONRequest);

needed to be changed to

     StringEntity se = new StringEntity(JSONRequest,"utf-8");

Thanks Jens, that one comment pushed me into the right direction.

Try this one, it's good for u

    private static String sendRequestPost(String url, Object obj) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpost = new HttpPost(url);
            if (obj != null) {
                httpost.setEntity(new StringEntity(new Gson().toJson(obj), "utf-8"));
                System.out.println("Request Json => " + new Gson().toJson(obj));
            }
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json; charset=utf8");

            HttpResponse response = httpClient.execute(httpost);

            HttpEntity responseEntity = response.getEntity();
            String strResponse = EntityUtils.toString(responseEntity);
            return strResponse;
        }
        catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM