I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.
Here is my code
try {
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com");
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}";
OutputStream os = conn.getOutputStream();
os.write(payload.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();
}
After following many posts and tutorials for more than 24 hours I got to know that I am not sending my URL parameters correctly. And also I learned that REST API call using ApacheHttpClient is comparatively easier. I resolved my HTTP error code 400 and got the response back from the server. Here is the working code for my issue.
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");
List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters
urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));
headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com"));
headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
for (NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
The API you are invoking needs a query parameter called "query=true|false".
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist?query=true");
After adding this param, the HTTP request itself succeeds with status code 200, but the REST call fails with some server side error. Maybe you need a different payload.
I suggest if you are new to REST, try a REST client like POSTMan
Related
I am trying to read the response body for an error response(404,400,500) using java application and basic http client. When testing in my local , I am able to get the proper json response. But when I deployed to azure I am getting the error response body in HTML tags.
Error response I got when deployed to azure and testing from there:
400 Error400 error while attempting to access resource
#AddLoggerInAppInsights
public Map exchangeNativeHttpRequest(String url, String jsonPayLoad, String correlationId) {
Map<String,Object> responseMap = null;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty(CLIENT_ID_KEY, System.getenv(CLIENT_ID_VALUE));
conn.setRequestProperty(CLIENT_SECRET_KEY, System.getenv(CLIENT_SECRET_VALUE));
conn.setRequestProperty(CORRELATION_ID, correlationId);
OutputStream os = conn.getOutputStream();
os.write(jsonPayLoad.getBytes());
os.flush();
HttpStatus httpStatus = HttpStatus.valueOf(conn.getResponseCode());
BufferedReader br = null;
if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_OK) {
br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
}else if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_BAD_REQUEST){
br = new BufferedReader(new InputStreamReader(
(conn.getErrorStream())));
}else {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
telemetryClient.trackEvent(correlationId+":" +"Response for Create Breakdown IBMI API from HTTP_CONNECTION: "+sb.toString());
responseMap = new HashMap<>();
responseMap.put("statusCode",httpStatus);
responseMap.put("response", sb.toString());
conn.disconnect();
} catch (MalformedURLException e) {
telemetryClient.trackException(e);
} catch (IOException e) {
telemetryClient.trackException(e);
}
telemetryClient.trackEvent(correlationId+":" +"Returned Response of Create Breakdown IBMI API from HTTP_CLIENT: "+responseMap.toString());
return responseMap;
}
Im trying to Update JSON data to Thingspeak channel, but i get 401 error Authorization error. Have sent "writekey" as parameter. Error is
{"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
` try {
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
NameValuePair nv5 = new BasicNameValuePair("writeApi_Key",writeApi_Key);
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpPut put= new HttpPut(urlname);
URI uri = null;
try {
uri = new URIBuilder(put.getURI()).addParameters(nvPairList).build();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
put.setURI(uri);
put.setHeader("writeApi_Key", writeApi_Key);
put.setHeader(HTTP.CONTENT_TYPE, "application/json");
put.setHeader("charset", "utf-8");
put.setHeader("Connnection", "keep-alive");
put.setHeader("Cache-Control", "no-cache");
System.out.println("Url header of post:::"+put.toString());
StringEntity entity = new StringEntity(entryobj.toString());
put.setEntity(entity);
System.out.println("Url header of post:::"+put.toString());
HttpResponse response = client.execute(put);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
System.out.println("connection refused");
} else if (response.getStatusLine().equals("0")) {
System.out.println("Update Failed");
}
HttpEntity responseentity = response.getEntity();
String responseString = EntityUtils.toString(responseentity, "UTF-8");
System.out.println(responseString);
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} `
output url is when writeApi_Key and api_key respectively checked outputs are below
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?writeApi_Key=UEDXXXXXXXXXXXXX HTTP/1.1
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?api_key+=VG2XXXXXXXXXXXXX HTTP/1.1
Kindly looking for some one who can shed throw light.. Thanks you so much..
Check to make sure that your API key is correct. Many people who have this problem are using zeros ('0') instead of the letter 'O', and vice-versa. '1' and 'l' can be a problem as well.
Please I have gone through all the question from stackoverflow, but those are not applicable to my problem.
Please have look in image request working fine from POSTMAN.
But When I tried from android code it is not working.
My Sample Android code is here.
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
URL url = new URL("sample url");
String postData = "key1=valu1&key2=valu2";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(55000 /* milliseconds */);
conn.setConnectTimeout(55000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os));
writer.write(postData);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
Log.e("response ",line);
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
} catch (Exception e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
}
}
}
}
Above java code return 405 error code. I also tried from OkHttp also.
Please help.
Putting a '/' at the end of URL causes the redirect to happen because your server likes urls that end in '/'. POST is fully supported by the URL your server redirects you to, but the client is executing a GET request when it behaves according to your setRedirecting() call (cURL does the same exact thing with the -L switch) The fix is to either put a '/' at the end of URL, or to grab the Location header from the response yourself and then initiate another POST request manually.
This can be observed in wireshark. You can test the theory by trying to perform a GET request with your browser to the URL with a slash appended to it. That will cause the browser to get a 405. Here's the fixed code for Android, this code uses the simple fix of appending a '/' to the URL (not production ready):
Read more from here.
Do let me know if this helps :)
Additionally, try using this piece of code:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://your URL");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Your API call is reciveving data in GET parameter. So data should send along with url as given below
String postData = Uri.encode("key1=valu1&key2=valu2");
URL url = new URL("sample url"+"?+postData);
I just had a similar problem with the HttpClient in Java. The solution was to specify the HTTP version explicitly:
HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
Now my requests returns the same result as through Postman.
public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
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();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.
I am trying to write a JSON Client which uses HTTP GET method,and I am getting an response of 500.The code I have tried is below,Is there any wrong with the same?The request parameter I am trying to set is entityName=Nila and parentEntity=500000001 as parameters.
URL url = new URL("http://192.168.210.74:9763/services/testEntityService?entityName=Nila&parentEntity=500000001");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
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();
}
}
Its an internal server error yes the problem is on server side.