How to use HTTP GET with Android? [duplicate] - java

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;
}

Related

POST string data with HttpUrlConnection as binary/octet in Android/Java

After some hours research, I haven't found any solution that contains my problem.
I have a String value that I want to send it via POST.
I've build something. I just don't know how to set that it will be send as binary/octet-stream.
String data = someData();
String sUrl = "http://some.example.website.com";
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) (new URL(sUrl)).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
I'm using HttpUrlConnection because I used DefaultHttpClient() that is deprecated.
I hope someone can help me!
Kind Regards!
You can use code like the below snippet:
HttpClient httpclient = new DefaultHttpClient();
String responseXml = null;
StringEntity se = "test string to be sent to the server";
HttpPost httppost = new HttpPost(temp);
try {
se.setContentType("text/soap+xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
responseXml = EntityUtils.toString(resEntity);
Log.d("Response XML", responseXml);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(TAG,e.getMessage());
} catch (ClientProtocolException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
} catch (Exception e){
e.printStackTrace();
Log.e(TAG,e.getMessage());
}
I used this code to send a xml to the server. You can replace what you want to send in the se variable.

Read json object from server

Hi I am new to android programming and I am working on a project that converts a list into json object and stores it in the server and retrieves it. I am able to send the json object to the server and store it but i am not able to retrieve it. What approach should i use to retrieve the json object stored on the server?
You can reffer bellow class ...... call getJSONfromURL(YOUR_JOSN_URL) and method will return you JSONObject.
I hope this will work
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
To retrieve JSON from server you have to establish a connection with server first by using DefaultHttpClient Hope you did that. If yes, post your code and if no then have look on
www.androidhive.info/2012/01/android-json-parsing-tutorial
Or google it you will lot of help to parse the JSON when you have URL with you.

JSON parsing for huge data

I have to download more than 40,000 json records from my web service, but it is taking so long time to download. The downloaded data is storing into a string, but I am not able parse that string. Please tell me a solution to solve this problem.
URL: https://buzoonga.co.uk/appapi/contacts.php?user_id=531
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
check out gzip. excellent text compressor. you are going to remove ~70% of the size :) you just have to gzip it serverside and unzip it clientside. if this overhead increases the time but the download is a third of the time, you might win in the end.
Also consider designing a better schema to reduce the size of your jsons.
Like, instead of "animalBodyParts" put "abp" or something. you have not put an example of your jsons so I am just guessing.
You can use the JSONTokener class and pass the InputStream
jObj = new JSONObject(new JSONTokener(httpEntity.getContent()));
To reduce the time to download you need to support gzipped downloads on the server side or change your JSON structure to a more compact array based format

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
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
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Android Httppost

Hi i am using below code to send data to server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("name", "dave"));
nameValuePairs.add(new BasicNameValuePair("taxi no", "354"));
nameValuePairs.add(new BasicNameValuePair("pack", "0"));
nameValuePairs.add(new BasicNameValuePair("exchk", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I can successfully send data to server,but the server return larger amount of data(100Kb-200KB) in text format.I want to convert that text response into json object.so i am assigning all the response into one string to convert json object.
But That Response string contain only less amount of data.
I checked the server it send 112kb file but that response String contain only less data.say around (50kb-75kb).
So can u please any one guide me to solve the problem
ArrayList is an expandable List item. So I have no idea what the purpose of using "5" as an argument. Second thing is BasicNameValuePair contains names and values as arguments. It is a good practice to use single word for a name attribute. Remove
String responseBody = EntityUtils.toString(response.getEntity());
Add following code sample
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
This return the page content in a readable format. Then you can pass it to a JSON file by using JSONObject and JSONArray.

Categories