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.
Related
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 want to get a String return type for a http response I get for http post request i trigger, but my return variable is giving error
"message cannot be resolved to a variable"
Subsequently I have to convert that return string value to a json string data.
here is my code....
public String sendPOST(String _postData) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(POST_URL);
httpPost.addHeader("User-Agent", USER_AGENT);
StringEntity entity = new StringEntity(_postData, HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpPost);
System.out.println("POST Response Status:: " + httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
String message = org.apache.commons.io.IOUtils.toString(reader);
String type = message.getClass().getName();
System.out.println(type);
System.out.println("Final : " + message);
}
reader.close();
// print result
System.out.println(response.toString());
httpClient.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
Because local "message" variable you are using outside of loop. Add global "message" variable, That should solve your problem.
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
I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}
I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it?
I've tried with the methods offered by the HttpReponse class but didn't find it.
Thanks
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
You can modify your code like this:
//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//edit: there is already function for this
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
//Houston we have a problem
//we should do something with bad http status
return null;
}
EDIT: just one more thing ...
instead of requestToString(..); you can use EntityUtils.toString(..);
Have you tried this?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
Have you tried the following?
response.getStatusLine().getStatusCode()