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.
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 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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how do perform Http GET in android?
I want to use the Google Products/Shopping API in my Android app but I don't know anything about HTTP GET. I'm reading this and it's giving me all these different web adresses to use. So how do I use the Google Products/Shopping API in Android with HTTP GET?
It is useful to get familiar with HTTP first, then with URLConnection and Apache HttpClient.
Here is some sample code where I get JSON from a server. It includes the basic code lines for connecting to something via HTTP.
public JSONArray getQuestionsJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
String jsonData = reader.readLine();
JSONArray jarr = new JSONArray(jsonData);
is.close();
return jarr;
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return null;
}
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.
I want to upload a txt file to a website, I'll admit I haven't looked into it in any great detail but I have looked at a few examples and would like more experienced opinions on whether I'm going in the right direction.
Here is what I have so far:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
And I call it as follows:
postPage("http://www.testwebsite.com", "data/data/com.testxmlpost.xml/files/logging.txt", true));
I want to be able to upload a file from the device to a website.
But when trying this way I get the following response back.
HTTP/1.1 405 Method Not Allowed
Am I trying the correct way or should I be doing it another way?
That code looks reasonable, the error is from the server and indicates that POST is not allowed for that page.
You're sending the literal string "data/data/com.testxmlpost.xml/files/logging.txt". If you want to post a file, use a FileEntity.