HTTP Post request Android - java

I am trying to contact an API from Android
I have found this sample code...
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
My question is, how can I see the response to insure it is getting one? IS there a way to add in an API key?
Also, does the "yoursite.com" have to be a PHP file?

HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
//read stream
//if expect binary data:
BufferedInputStream stream = new BufferedInputStream(instream);
int maxBytes = 128 * 1024;
if(entity.getContentLength() > maxBytes) {
throw new IllegalArgumentException("Much too big!");
}
byte[] bytes = new byte[(int) entity.getContentLength()];
int offset = 0, count = bytes.length;
while(stream.read(bytes, offset, count) > -1 && count > 0) {
count -= offset;
}
final Bitmap responseImage = BitmapFactory.decodeByteArray(
bytes, 0, bytes.length);
//or if you expect text
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream, Charset.forName(
entity.getContentEncoding().getValue())));
StringBuffer buffer = new StringBuffer();
String line;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
final String responseText = buffer.toString();
} finally {
instream.close();
}
}

Watch these videos (YouTube Link)
It is a 6-part tutorial of making a log-in app for android.
It also shows how to create a database with MySQL. Hope it helps.

Related

Making a POST request in Android

I'm trying to make a POST request to a server in my Android app, but it ain't happening. Below is the code -
try{
View p = (View) v.getRootView();
EditText usernamefield = (EditText)p.findViewById(R.id.username);
String username = usernamefield.getText().toString();
EditText passwordfield = (EditText)p.findViewById(R.id.pass);
String password = passwordfield.getText().toString();
String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";
Log.i(TAG,password);
String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();
Log.i(TAG,authToken);
HttpClient client = new DefaultHttpClient();
Log.i(TAG,"after client1");
HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
Log.i(TAG,"after client2");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i(TAG,post.getURI().toString()); //logs the URL
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
Log.i(TAG,"Status code is"+status);
Log.i(TAG,"after post");
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
{
Log.i(TAG,"bad http response");
Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
System.out.print(sb.toString());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NoSuchAlgorithmException e)
{
}
catch(Exception e){
}
The code executes till the Log.i(TAG,post.getURI().toString()) log statement. It'll print out the URL that is made - http://ws.audioscrobbler.com/2.0/. No parameters attached (which is weird).
I don't know what's wrong with my implementation for adding parameters to URL using NameValuePairs.
I do have one simple method to post data to server. Please use it and let me know if that is useful to you or not:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");
public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
url = url.trim();
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpPost httpPost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
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, "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 jObj;
}
You must have wrapped this code in a try catch block since there are several possible exceptions thrown here. As to which is the problem I am not sure, but here are some common ones that could cause a problem and you need to give more info before we can see which one it is:
1) On newer versions of Android if you make thisw call in the main UI thread it will throw an exception a NetworkOnMainThread exception. You must do networking code on a background thread.
2) You did not declare the Internet permission in your manifest so it will throw a security exception.
You need to look at the logcat for an exception or break in the catch part of your try/catch. If your catch looks like this:
catch(Exception e)
{
}
Then it will silently eat the exception and give you no indication of the problem.
Just try with JsonStringer.Like:
HttpPost request = new HttpPost("http://ws.audioscrobbler.com/2.0/something_here");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("method")
.value("auth.getMobileSession").key("api_key").value(apikey)
.key("api_sig") .value(authSig).key("format").value("json").key(authToken).value(authToken).key("username").value(username)
.endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Also as Kaediil said make try and catch clause with your response code.

generate byte array from StringBuffer.toString

What I'm trying to do is to generate a byte array from a url.
byte[] data = WebServiceClient.download(url);
The url returns json
public static byte[] download(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
StatusLine status = response.getStatusLine();
int code = status.getStatusCode();
switch (code) {
case 200:
StringBuffer sb = new StringBuffer();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
is.close();
sContent = sb.toString();
break;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sContent.getBytes();
}
This data is used as a parameter for String
String json = new String(data, "UTF-8");
JSONObject obj = new JSONObject(json);
for some reason, I get this error
I/global ( 631): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
I think something there must be missing here sContent = sb.toString(); or here return sContent.getBytes(); but I'm not sure though.
1. Consider using Apache commons-io to read the bytes from InputStream
InputStream is = entity.getContent();
try {
return IOUtils.toByteArray(is);
}finally{
is.close();
}
Currently you're unnecessarily converting the bytes to characters and back.
2. Avoid using String.getBytes() without passing the charset as a parameter. Instead use
String s = ...;
s.getBytes("utf-8")
As a whole I'd rewrite you're method like this:
public static byte[] download(String url) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
StatusLine status = response.getStatusLine();
int code = status.getStatusCode();
if(code != 200) {
throw new IOException(code+" response received.");
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
try {
return IOUtils.toByteArray(is);
}finally{
IOUtils.closeQuietly(is.close());
}
}

Post url from android to retrieve data

i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json
what i want is to post this url from android to get that json data into androids view .
any help is highly appreciated
thanks
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
response variable will contain your json data.
Here is a function maybe you can use to post a string to a URL.
public String doHttpPost(final String fullUrl, final String body) {
final URL url = new URL(fullUrl);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// set the request mode as POST
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-charset", "utf-8");
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
// write the body.
request.writeBytes(body);
// flush output buffer
request.flush();
request.close();
// construct a read using input stream and charset.
final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
final BufferedReader in = new BufferedReader(isr);
String inputLine;
final StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine).append("\n");
}
in.close();
isr.close();
urlConnection.disconnect();
return stringBuilder.toString();
}
check below code: try this it may help you.
ArrayList nameValuePairs1 = new ArrayList();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
result is a json String. parse that json and display in any control. i displaied that in text view see below.
final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (Name.length() > 0 && Name != null) {
txtvenue.setText(Name);
} else {
txtvenue.setText(venue_name);
}
}
};
new Thread() {
public void run() {
try {
// put your result here
JSONObject jObject = new JSONObject(result);
JSONObject menuObject = jObject.getJSONObject("response");
JSONObject venueObject = menuObject.getJSONObject("venue");
Name = venueObject.getString("name");
String id = venueObject.getString("id");
Log.d("--------name---------", Name);
Log.d("--------id---------", id);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();

How to Get Response From HttpClient in Android 4.0

i have some trouble when i used this code in android 4.0 i did not get Response but i got Response in 2.2,2.3,2.3.3 version
List<NameValuePair> pwadd = new ArrayList<NameValuePair>();
pwadd.add(new BasicNameValuePair("UName", UName));
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(
"http://10.0.2.2/new/webser/Load.php");
httppost.setEntity(new UrlEncodedFormEntity(pwadd));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String response = sb.toString();
what should i do in this code to run in android 4.0 version?
try these in an async task. you need to make network stuff in a separate thread anyway
public static String PrepareSendPostData_DetailsActivity(String station_id) {
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url here");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(100);
nameValuePairs.add(new BasicNameValuePair("param_1", "value_1"));
nameValuePairs.add(new BasicNameValuePair("param_2", "ok"));
nameValuePairs.add(new BasicNameValuePair("module", "dbgestion"));
nameValuePairs.add(new BasicNameValuePair("pdv_id", station_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = getResponseBody(response);
if (responseBody != null)
return responseBody;
else
return null;
} catch (ClientProtocolException e) {
Log.e("exception here", e.getMessage().toString());
return null;
} catch (IOException e) {
Log.e("exception here 2", e.getMessage().toString());
return null;
}
}
public static String getResponseBody(HttpResponse response) {
String response_text = null;
HttpEntity entity = null;
try {
entity = response.getEntity();
response_text = _getResponseBody(entity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e1) {
}
}
}
return response_text;
}
public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
hope it helps...

Slow upload speeds using HttpClient, Jame's Mime4j and HttpPost method of posting

I'm uploading a multipart chunk of data using HttpPost and feeding it into an HttpClient objects execute method as follows:
HttpPost loginPost = new HttpPost(LOGIN_URL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("_email", mEmailAddress));
params.add(new BasicNameValuePair("lpassword", mPassword));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
loginPost.setEntity(entity);
HttpResponse resp = mHttpClient.execute(loginPost);
HttpPost post = new HttpPost(UPLOAD_URL);
FileBody bin = new FileBody(file);
MultipartEntity me = new MultipartEntity();
me.addPart("stuff", new StringBody(stuff));
me.addPart("file", bin);
post.setEntity(new RequestEntityEx(me, handler));
mHttpClient.execute(post);
Now, logging in and posting work - fine but uploading is painfully slow. I've tested my internet connection and it's far slower than what it should be (approx. up speed is 1Mb/s, uploading a 3MB file is taking around 5 minutes (rather than 30s).
Anyone have any ideas?
I've found that HttpClient is like 9 times slower than regular way on https. I have no idea why, anybody knows what's wrong.
Here is basically my code
private static HttpClient httpClient = new DefaultHttpClient();
private static HttpPost httpPost = new HttpPost(RRD_URL);
public static String sendData(List<NameValuePair> data) {
StringBuffer buffer = new StringBuffer();
BufferedReader rd = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse httpResponse = httpClient.execute(httpPost);
rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace(System.out);
} finally {
try {
if (rd != null) {
rd.close();
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
return buffer.toString();
}

Categories

Resources