android XML send and get receive via HTTP post - android

first I'm trying to be able to send a HttpResponse with parameters such as:
http://www.syslang.com/frengly/controller?action=translateREST&src=en&dest=iw&text=good&email=YYY&password=XXX
the code looks something like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.syslang.com/frengly/controller");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("src", "en"));
pairs.add(new BasicNameValuePair("dest", "iw"));
pairs.add(new BasicNameValuePair("text", "good"));
pairs.add(new BasicNameValuePair("email", "YYY"));
pairs.add(new BasicNameValuePair("password", "XXX"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
the API structure is available at http://www.frengly.com/ (under the API tab) and has a total of 5 parameters (src, dest, text, email, password).
so far every time I tried to call
HttpResponse response = httpClient.execute(httpPost);
I keep getting an IO Exception :(
After that I should get something like this structure:
-<root>
<text>good</text>
<translation>טוב</translation>
<translationFramed>טוב|</translationFramed>
<missing/>
<existing>good,</existing>
<stat>1/1</stat>
</root>
I think I'll handle this part to build XML and parse it as I need
p.s: I checked
Android, send and receive XML via HTTP POST method
and many other links, which didn't help me a lot.
let me know if any code lines from my application needed...
Thanks in advance.

You don't need to POST.
You need to GET instead.
// Construct your request here.
String requestURL= "http://www.syslang.com/frengly/controller?action=translateREST&src=en&dest=iw&text=good&email=YYY&password=XXX"
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestURL);
HttpResponse response = httpClient.execute(httpGet);
And also internet permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<application
....
....

Related

Android cant execute POST request after GET

My problem is this: after the GET request authorization and save cookies trying to perform a POST request to add data, but the server responds with 500 code. What's funny, because if POST query string form in a browser, it is executed correctly. The code below.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(site + "/admin/users/login_do/?login=admin&password=demo");
HttpResponse response = httpclient.execute(httpget);
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
HttpPost httppost = new HttpPost(site + "/admin/news/add/5/item/do/");
httppost.addHeader("Cookie", "PHPSESSID="+cookies.get(0).getValue()+"; umicms_session="+cookies.get(1).getValue()+"; stat_id="+cookies.get(2).getValue());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("active", "1"));
nameValuePairs.add(new BasicNameValuePair("name", "test"));
nameValuePairs.add(new BasicNameValuePair("data[new][anons]", "anno"));
nameValuePairs.add(new BasicNameValuePair("data[new][content]", "cont"));
nameValuePairs.add(new BasicNameValuePair("data[new][publish_time]", "1420202020"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = httpclient.execute(httppost);
StatusLine status = response.getStatusLine();
Log.d("my",String.valueOf(status.getStatusCode()));
Log.d("my",String.valueOf(status.getReasonPhrase()));
I've tried to run POST using HttpURLConnection, but also received 500 response.
Who can tell what might be the problem?
Problem solved. I Forgot to send csrf token with POST request and set Referer header
nameValuePairs.add(new BasicNameValuePair("csrf", csrf));
httppost.addHeader("Referer", referlink);

posting the data using httpput in android

I have a problem in posting the data to server by using httpput methods in android.I have to send feedback to server and getting json response. but i am getting 404 bad request. but i dont know where is the problem.
I am strucked here and didn't find any solution. Any suggestions?
My code is as follows:
HttpClient client = new DefaultHttpClient();
HttpPut put = new HttpPut(getString(R.string.feedBack));
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("userId", "8"));
pairs.add(new BasicNameValuePair("feedback",feedbackMessage
.getText().toString()));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
Log.d(tag, "Result" + response.getStatusLine());
You are not initializing a URL object and passing in simple String.
You should do this instead:
URL url = new URL(getString(R.string.feedBack));
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
And it should work.

The JSON object sent from android application is null when i want to access him in java servlet

I am writing an application in android and i am sending a json object to a java servlet.
This is the android code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
JSONObject jsonObjectToPass = returnJsonStringObject();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("jsonGPSParameter",jsonObjectToPass.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(entity);
response = httpClient.execute(post);
This is the java servlet code
request.getParameter("jsonGPSParameter");
The problem is that the getParameter() method return null.
Im not be able to spot the problem.
If someoane can help me it would be a great help.
Thanks
For the code to work proper i have to remove the next to lines from android code:
entity.setContentType("application/json");
post.setHeader("Content-type", "application/json");

How to encode space as %20 in UrlEncodedFormEntity while executing apache HttpPost?

The web serive i am hitting requires the parameters as URLEncodedFormEntity. I am unable to change space to %20 as per requirement of the web service, instead space is converted to +.
My code is :
HttpClient client = new DefaultHttpClient()
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
HTTP.UTF_8);
post.setEntity(entity);
HttpResponse resp = client.execute(post);
where parameters is List<NameValuePair> parameters.
I read through many posts and all suggest manuall change space to %20 after emcoding. Here, how do i access the entity and change it manually?
Any help will be appreciated.
The UrlEncodedFormEntity is basically a StringEntity with a custom constructor, you don't actually have to use it in order to create a usuable entity.
String entityValue = URLEncodedUtils.format(parameters, HTTP.UTF_8);
// Do your replacement here in entityValue
StringEntity entity = new StringEntity(entityValue, HTTP.UTF_8);
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
// And now do your posting of this entity
Jens' answer works like a charm!. To complete his example this what I was using to post a parameter:
String label = "A label";
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("label", label));
httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
But it always posts the "+" string, I mean, "label=A+label". Using Jens' suggestion I changed my code to:
String label = "A label";
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("label", label));
String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8);
entityValue = entityValue.replaceAll("\\+", "%20");
StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
httpget.setEntity(stringEntity);
Now it posts "label=A%20label"

Loop HttpPost requests

I need to access data from a webpage using several different post requests. For now I use:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://myurl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "search"));
nameValuePairs.add(new BasicNameValuePair("ndc", ndc));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
I need to sent this request using different values for the variable ndc. Would looping this lines be a good idea? If so, how to reuse the HttpClient and HttpPost variables?
If the URL needs to stay the same, then you should only change the values that need to sent.
for (int i=0; i<ndcArray.length;i++)
{
if(i==theNumberWhenURLhasToBeChanged) //adjust this condition based on your knowledge when the url has to be changed, lets say if i > theNumberWhenURLhasToBeChanged, then change the url...
{
httppost = new HttpPost(URLs[theNumberWhenURLhasToBeChanged]);
}
nameValuePairs.add(new BasicNameValuePair("ndc", ndcArray[i]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
Note that: response will change each time, so bear in mind that you should save the response somewhere. And ndcArray[] can be replaced with any structure you want.

Categories

Resources