Alternative for UrlEncodedFormEntity for sending data via POST - android

When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);

Related

android XML send and get receive via HTTP post

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
....
....

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 send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

Android HTTPRequest Cycle

I am trying to send JSON to my server and retrieve a JSON in return as a result.
Like sending in username and password and getting back token and other content.
This is what i am doing for the HTTP Request for sending. How do i now retrieve back the content in the same request ?
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://192.168.1.5/temp/test.php");
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name", jsonStr));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
String[] status_String=res.getStatusLine().toString().trim().split(" ");
//String hd=res.getFirstHeader("result").toString();
//System.out.println("Res=" + res);
Log.e("tag", ""+res.toString());
if(status_String[1].equals("200")){
isDataSent=true;
Let me add more in vvieux's answer:
res.getEntity().getContent()
will return you InputStream.
String returnData = EntityUtils.toString(res.getEntity());
You can use the HttpEntity
res.getEntity().getContent()

Categories

Resources