Android - Http Get Request - java

I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}

I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.

Related

send arabic words with http request GET android

i Want to send arabic (unicode) with the HTTP Request
When using URLEncodedUtils.format(params, HTTP.UTF_8);
it give paramString this value when the words are in arabic
"%D8%A7%D9%84%D9%82%D8%A7%D9%87%D8%B1%D9%87"
This is my code:
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
Log.d("Parser" , paramString);
url += "?" + paramString;
Log.d("parser" , url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
The Server Code
function getShippingAddress($email)
{
$customerAddress = Mage::getModel('customer/address');
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
$defaultShippingId = $customer->getDefaultShipping();
$customerAddress->load($defaultShippingId);
$response["success"] = 1;
$response["data"][0] = $customerAddress->getData('city');
$response["data"][1] = $customerAddress- >getData('street');
$response["data"][2] = $customerAddress->getData('telephone');
header('Content-Type: application/json; charset=utf-8');
return json_encode($response);
}
Try sending parameter using POST. Sample code is here:
private String sendHttpPost(String url, String msg)
throws Exception {
HttpPost post = new HttpPost(url);
StringEntity stringEntity = new StringEntity(msg, "UTF-8");
post.setEntity(stringEntity);
return execute(post);
}
or try this :
String unicodeUrl = URLEncoder.encode(url += "?" + paramString, "UTF-8");
HttpPost post = new HttpPost(unicodeUrl);
UPDATE:
if your params ="Some_String_In_Arabic", try this code :
DefaultHttpClient httpClient = new DefaultHttpClient();
//String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String unicodeUrl = URLEncoder.encode(url += "?" + params, "UTF-8");
Log.d("URL" , unicodeUrl);
HttpGet httpGet = new HttpGet(unicodeUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
and use urldecode method (of PHP) in your server side to get the string back in arabic form.

How to send Json String using REST to java webservice in Parameter in android?

Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}

Getting "Invalid JSON primitive" error while trying to get data from WebService

I'm working on an android app and I want to get some data from a WebService. I'm using this code to get JSON data from the WebService.
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_ActiveFair";
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("error!!",e.toString());
}
It works correctly an I get the data like this:
{
"d": "{\"Id\":2,\"Name\":\"Fair Name \",\"IsActive\":true,\"Date_Start\":\"\\/Date(1383343200000)\\/\",\"Date_End\":\"\\/Date(1384034400000)\\/\",\"Url_Map\":null,\"Details\":\"Fair Details \",\"Address\":\"FairAdress \",\"VisitingInfo\":\"Fair Visiting Info\",\"Contact\":null,\"Transportation\":\" Fair Transportation Info \"}"
}
But when I want to use another method in the webservice which needs to get FairId I get the result:
{
"Message": "Invalid JSON primitive: FairId.",
"StackTrace": " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.ArgumentException"
}
And here is my code to run the Get_EventList method:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
List<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("FairId", "2"));
post.setEntity(new UrlEncodedFormEntity(postParameters));
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}
What can be the problem? How can I solve it?
I solve the problem by sending FairId to WebService with JSONObject. Here is my new code:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
JSONObject json = new JSONObject();
json.put("FairId", "2");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}

Use arabic text in android

How to get the arabic string in json format and how to display in android application
inputStreamReader. I get the json from server side And using the Windows-1256 encodingString to convert the arabic string but sometext not be shown correctly.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
System.out.println(url + ":::url");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream,"windows-1256");
//new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,8);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You

HttpGet adding header

I am creating a httpClient and I want to add certain header to my HttpGet request
My current code produces the following request.
GET /folder/index.html HTTP/1.0
Host: localhost:4444
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
What I want is to add another header (If-Modified-Since) in that request .
How can I do it?
Thank you :)
public String httpGet(String s) {
String url = s;
StringBuilder body = new StringBuilder();
httpclient = new DefaultHttpClient(); // create new httpClient
HttpGet httpGet = new HttpGet(url); // create new httpGet object
try {
response = httpclient.execute(httpGet); // execute httpGet
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// System.out.println(statusLine);
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection(); // stop connection
}
return body.toString(); // return the String
}
Use the setHeader() method on the HttpGet object like follows.
httpGet.setHeader("If-Modified-Since","11/26/2012");
I used this JavaDoc as a reference.
Use the setHeader() method on the HttpGet object like follows for the first one
httpGet.setHeader("If-Modified-Since","11/26/2012");
and then use addHeader() method on the HttpGet object like as follows for the second header.
httpGet.addHeader("If-Expires-On","11/26/2014");

Categories