I have a code like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(server);
try {
JSONObject params = new JSONObject();
params.put("email", email);
StringEntity entity = new StringEntity(params.toString(), "UTF-8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setEntity(entity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost, responseHandler);
JSONObject response = new JSONObject(responseBody);
fetchUserData(response);
saveUserInfo();
return true;
} catch (ClientProtocolException e) {
Log.d("Client protocol exception", e.toString());
return false;
} catch (IOException e) {
Log.d`enter code here`("IOEXception", e.toString());
return false;
} catch (JSONException e) {
Log.d("JSON exception", e.toString());
return false;
}
And i want to have a response even if I have HTTP 403 Forbidden to get error message
The BasicResponseHandler only returns your data if a success code (2xx) was returned. However, you can very easily write your own ResponseHandler to always return the body of the response as a String, e.g.
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return EntityUtils.toString(response.getEntity());
}
};
Alternatively, you can use the other overloaded execute method on HttpClient which does not require a ResponseHandler and returns you the HttpResponse directly. Then call EntityUtils.toString(response.getEntity()) in the same way.
To get the status code of a response, you can use HttpResponse.getStatusLine().getStatusCode() and compare to to one of the static ints in the HttpStatus class. E.g. code '403' is HttpStatus.SC_FORBIDDEN. You can take particular actions as relevant to your application depending on the status code returned.
According to the documentation for BasicResponseHandler:
If the response was unsuccessful (>= 300 status code), throws an HttpResponseException.
You could catch this type of exception (Note: you are already catching the supertype of this exception ClientProtocolException) and you could put some custom logic in that catch block to create / save some response when you encounter an error situation, such as the 403.
Related
Am trying to create user into my salesforce account through REST api using java.But its returning 400 status code.Can you please guide me?
Here is the code am trying:
public static void createUsers() {
System.out.println("\n_______________ USER INSERT _______________");
String uri = baseUri + "/sobjects/User/";
System.out.println(uri);
try {
//create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("FirstName", "Jake");
lead.put("LastName", "sully");
lead.put("Alias", "Jake");
lead.put("Email", "Jake#gmail.com");
lead.put("Username", "Jake#gmail.com");
lead.put("Name", "jake");
lead.put("UserRoleId","00E28000000oD8EEAU");
lead.put("Id", "10028000000GLSIAA4");
lead.put("EmailEncodingKey", "ISO-8859-1");
lead.put("TimeZoneSidKey", "Asia/Kolkata");
lead.put("LocaleSidKey", "en_US");
lead.put("ProfileId", "00e280000027hnGAAQ");
lead.put("LanguageLocaleKey", "en_US");
//Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
System.out.println(response.toString());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved lead id to use when we update the lead.
leadId = json.getString("id");
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
I have a httpClient function which returns an HttpResponse object to the calling function.
public HttpResponse postRequest(String uri, String body) throws IOException {
HttpResponse response;
String url = baseUrl + uri;
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.build()) {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(body));
post.setHeader(AUTHORIZATION_HEADER, authorization);
post.setHeader(CONTENTTYPE_HEADER, APPLICATION_JSON);
post.setHeader(ACCEPT_HEADER, APPLICATION_JSON);
response = httpClient.execute(post);
} catch (IOException e) {
System.out.println("Caught an exception" + e.getMessage().toString());
logger.error("Caught an exception" + e.getMessage().toString());
throw e;
}
return response;
}
In my calling function I call, HttpResponse response = httpRequest.postRequest(url,body); (where httpRequest is an object for the class which contains the function
When I try to parse the contents of the received the response through
String responseString = IOUtils.toString(response.getEntity()
.getContent(), "UTF-8");
I get an error Socket is closed.
How do I use the contents of HttpResponse once the connection is closed?
Your try-with-resources statement is closing the entire client. You don't want that. Remove it. You want the close to happen when the caller closes the response you're returning.
I am fairly confident this code works (I used it in another part of my project for a different API) as far as posting but I do not think the URL is being formatted correctly. I want to know if there is anyway to view the full URL after building all of the entities so I can see if the final URL is formatted correctly. Code:
My URL = http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php
Method = POST
API key = not going to post (works though)
drugName = just a string that has the name of a drug
I have logs in the code to try and view the url but they aren't returning anything close and the debugger isn't either.
I am trying to build the URL to look like this:
http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=My_API_KEY&ingredient=diovan
public String makeServiceCallPillBox(String url, int method,
String api, String drugName)
{
String resultEnitity = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpEntity entityResult = null;
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
// Butild the parameters
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("key", api);
builder.addTextBody("ingredient", drugName);;
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
Log.d("url", httpPost.toString());
httpResponse = httpClient.execute(httpPost);
Log.d("post", builder.toString());
Log.d("post2", entity.toString());
entityResult = httpResponse.getEntity();
resultEnitity = EntityUtils.toString(entityResult);
Log.d("result", resultEnitity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEnitity;
}
Any help is appreciated.
I am trying to send HTTP request. Currently I am stuck on adding Content-Length property: I have
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("Content-Length", ""+json.length() );
If i comment last line (content-length) server returns me error that I miss smth, I last line stays uncommented - then I catch an exception when trying to do
HttpResponse httpResponse = httpclient.execute(httpPost);
Please, tell me what am I doing wrong with setting headers.
PS I am sending easy JSON object
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
My full code snippet of post metod:
public static JSONObject POST(String url, String phone){
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
Log.d("ANT", "JSONObject jsonObject = new JSONObject(); PHONE:"+phone);
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
// 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);
Log.d("ANT", "json"+json.length());
// 7. Set some headers to inform server about the type of the content
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;");
// httpPost.addHeader("Content-Length", ""+json.length() );
// 8. Execute POST request to the given URL
Log.d("ANT", "httpPost:"+getStringFromInputStream(httpPost.getEntity().getContent()));
for (Header s : httpPost.getAllHeaders())
Log.i("ANT", "header::"+s.getName() + ":"+s.getValue());
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Log.d("ANT", "httpResponse.getEntity().getContent();");
// 10. convert inputstream to string
if (inputStream != null) {
result = getStringFromInputStream(inputStream);
Log.d("ANT", "getStringFromInputStream : "+result);
JSONObject obj = new JSONObject(result);
Log.d("ANT", "JSONObject");
return obj;
}
else
result = "Did not work!";
} catch (ClientProtocolException e) {
Log.d("ANT", "ClientProtocolException : "+ e.getLocalizedMessage());
} catch (IOException e) {
Log.d("ANT", "IOException:"+ e.getLocalizedMessage());
} catch (Exception e) {
Log.d("ANT", "Exception:"+ e.getLocalizedMessage());
}
// 11. return result
return null;
}
Can you elaborate on what the server error code is and a stack trace when the exception occurs?
Edit:
I tried some part of your code. I did not set the Content-Length (since this should be done automatically):
public class App
{
public static void main( String[] args )
{
post("http://www.baidu.com","+8912345");
}
public static JSONObject post(String url, String phone){
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("phone", phone);
// 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.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;");
// 8. Execute
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
} catch (ClientProtocolException e) {
System.out.println("ClientProtocolException : "+e.getLocalizedMessage());
} catch (IOException e) {
System.out.println("IOException:"+ e.getLocalizedMessage());
} catch (Exception e) {
System.out.println("Exception:"+ e.getLocalizedMessage());
}
return null;
}
}
I used wireshark and could verify that the following request is going to baidu:
POST / HTTP/1.1
Accept: application/json
Content-Type: application/json;
Content-Length: 20
Host: www.baidu.com
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.6 (java 1.5)
{"phone":"+8912345"}
This shows that the request is sent properly, which means the client side seems to be fine. That's why I would suggest to check the server side for errors. As I already mentioned I think you should use tcpdump or wireshark to check the traffic between client and server. This might give you a better understanding of what is going wrong.
http://www.webservicex.net/country.asmx?op=GetISD this is web service i want to parse and get code suppose if pass india then it should return.
public String CountryName(String Country)
{
HttpClient httpclient=new DefaultHttpClient();
HttpGet htpget=new HttpGet("http://www.webservicex.net/country.asmx?op=GetISD");
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htpget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, 5000).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", 5000).show();
} catch (IOException e) {
Toast.makeText(this, "Error", 5000).show();
}
return code;
}
I am getting Response code 200 But i am Unable to do Dom Parsing please help how i will implemnt how i will get code from DOm Parsing .
System.InvalidOperationException: Request format is invalid: .
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
This Error is coming
http://developer.android.com/reference/org/apache/http/HttpResponse.html
Youre only using the .getStatusLine() - isnt it just response.toString()?
I'd suggest using ksoap2. The code to parse response looks like this:
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
parseResponse(is, envelope);
and the response will be in the envelope.bodyIn property - it is very similar to json objects
private static void parseResponse(InputStream is, SoapEnvelope envelope)
throws Throwable {
try {
XmlPullParser xp = new KXmlParser();
xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
xp.setInput(is, "UTF-8");
envelope.parse(xp);
} catch (Throwable e) {
Log.e(LOG_TAG, "Error reading/parsing SOAP response", e);
throw e;
}
}
You can use the following URL to use simple http request:
"http://www.webservicex.net/country.asmx/GetISD?CountryName="+yourCountryName
It gives XML response directly.