Posting JSON object in HTTP in Java class - java

This is the error I am getting when I post a JSON as json.toString()
Am stuck with this problem. Need help to overcome this as early as possible
Error code -415
Unsupported Media Type.
Code is
String url = "http://0.0.0.0:0000/XXXX/XXXX?wsdl";
HttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("headerValue", "HeaderInformation");
//setting json object to post request.
JSONObject jsonObject=jsonValue();
if(jsonObject!=null ){
StringEntity entity = new StringEntity(jsonObject.toString(), "UTF8");
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
//this is your response:
HttpResponse response = client.execute(post);
System.out.println("Response: " + response.getStatusLine());
System.out.println(response.getStatusLine().toString());
}else{
System.out.println("jsonObject is Empty");

This means that your service that is accepting the post does not accept te media type you provide. It is probably annotated with #Consumes (something). You need to find what something is it. You have to specify the media type explicitly when posting.
For example JAX-RS client API:
Client client = ClientBuilder.newClient(new ClientConfig()
.register(MyClientResponseFilter.class)
.register(new AnotherClientFilter()));
String entity = client.target("http://example.com/rest")
.register(FilterForExampleCom.class)
.path("resource/helloworld")
.queryParam("greeting", "Hi World!")
.request(MediaType.TEXT_PLAIN_TYPE)
.header("some-header", "true")
.get(String.class);
In your case you need to change:
.request(MediaType.TEXT_PLAIN_TYPE)
Look here: Jersey Client API

Related

Java/Json - How to add/pass an ApiKey in the HttpPost request header?

I don't want to pass the apiKey using request.setEntity() method. I only want to pass it in the request header. Is it correct if I name the header as "Authorization"? Please correct me if what I'm doing is wrong.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(restAPIServiceURL);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept","application/json");
request.addHeader("Authorization","apiKey=AIzaSyCXhu........");
request.setEntity(new StringEntity(jsonString)); //I have other data to pass as Entity.
HttpResponse response = httpClient.execute(request);
Is there any other better way to pass the apiKey in the request header?
Yes. You can use this
String API_KEY = "YOUR API KEY";
String basicAuth = "Basic" + new String(Base64.encode(API_KEY.getBytes(), Base64.DEFAULT));
request.addHeader("Authorization", basicAuth);

pass json string to Post method

I have a json string, I want to pass it to POST method. But the 'execute', and 'executeMethod ' are throwing error as below:
"The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (PostMethod)". i have included the depencencies.
my code:
StringRequestEntity requestEntity = new StringRequestEntity(
json-string,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("myUrl");
postMethod.setRequestEntity(requestEntity);
HttpResponse response = httpclient.execute(postMethod);
Is there any alternative way to do this? please help. thanks in advance
I use Apache HttpClient.
Snippet for calling a post method is as below.
String JSON_STRING="{"name":"Example"}";
StringEntity requestEntity = new StringEntity(
JSON_STRING,ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);

Use Java to get Github repositories

I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.

Method to convert JSONObject to List<NameValuePair>

Hi iam creating an android application. In my application i have some form fields like edittext and radio buttons i am creating a JSONObject by retrieving text from all the form fields. JsonObject is created successfully. Now i want to pass this object to my PHP page where i have written code for getting this details and storing it in database. My problem is i am not understanding how to send this JSON object through httpPost or httpGet method. Only way i know is send parameters through List<NameValuePair> so i'm trying to convert JSONObject to List<NameValuePair>. Can anybody provide a method which can directly convert my JSONObject to List<NameValuePair>. Is there any predefined method for doing this. Or can any one provide solution where i can directly send by JSONObject to PHP and retrieve there.
Pass your JSONObject as a string to the String Entity constructor and then pass it to setEntity()
Sample:
HttpPost request = new HttpPost("//website");
StringEntity params =new StringEntity("passmyjson=" + yourJSONOBject.toString());
request.addHeader("content-type", "//header");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
in php File to check that it works;
<?php
print_r($_POST);
$json_string = $_POST['passmyjson'];
$json = json_decode($json_string);
print_r($json);
?>
You can do that with Apache HttpClient. I assume you have already a PHP handler that handles this request. Simply,
Create your JSONObject
Put your desired values
Send that json to php handler
You need to send request as application/x-www-form-urlencoded
Let's call url : http://your_php_service.com/handleJson;
HttpClient httpClient = new DefaultHttpClient();
JSONObject json = new JSONObject();
json.put("key", "val");
try {
HttpPost request = new HttpPost("http://your_php_service.com/handleJson");
StringEntity params = new StringEntity("json=" + json.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
httpClient.getConnectionManager().shutdown();
}
The format of request param will be ;
json={"key": "val"}
And you can handle this on php side like;
<?php
.....
$json = $_POST["json"]; // This will be json string
.....
Thank you all i got it
I added the following lines to my android Activity class
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse;
HttpPost httppost = new HttpPost(link); //-->link is the php page url
httppost.setEntity(new StringEntity(obj.toString())); //-->obj is JSONObject
httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
and in my php file i have added the following code
$msg=json_decode(file_get_contents('php://input'), true);
To get particular value from recieved Json string i added this $data = $msg['name'] ;
It is working

HttpPost response doesn't return the json object

I'm currently working on a project which needs to send a post request and get a json object from the server. Earlier I used Get method to access the json object. It worked fine. But because of some server changes I had to move to post method. Then it doesn't return me the json object that I got earlier from the 'get' method. I tried my best to come up with a solution but couldn't. Highly appreciate if anyone can help me to get through this problem.
private AdSniperAdObjectResponse postData(String url) {
//Bundle b = new Bundle();
HttpClient httpClient = HttpClientFactory.getThreadSafeClient();
//Log.d(TAG, "url: " + url);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "JSON");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("latitude", "-33.8736"));
nameValuePairs.add(new BasicNameValuePair("longitude", "151.207"));
nameValuePairs.add(new BasicNameValuePair("age", "35"));
nameValuePairs.add(new BasicNameValuePair("gender", "All"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String resp = EntityUtils.toString(resEntity);
Above is the code that I use. Earlier I used HttpGet class. For HttpPost, the 'resp'variable is always null. Don't know what I did wrong.
should't this be like
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
String resp = httpResponse.toString();
and in case if server return JSONString..
say JSONObject data = new JSONObject(resp);
and then get values..
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof (List<NameValuePair> ));
try with this and pass your data using this
jsonSerializer.WriteObject(reqStream, nameValuePairs );
reqStream.Close();
and again deserialize the response whatever you are getting
Before you attempt to get the HttpEntity, you should get the StatusLine and check that the status code is what you expect. I suspect that the real problem is that the server is sending an error response of some kind. And since you used an "Accept" header to request a JSON response, it is likely that the server is not sending any diagnostics in the response body ... so it is empty.
Guys I found the solution. It worked when I commented the following two lines.
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "JSON");
So thanks everyone for your answers. Highly appreciate.

Categories