I will Download XML File with Android 4.0 my old Code works at Android 2.3.3 here:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
I must have an Example without DefaultHttpClient .
From Gingerbread (2.3) and up, the preferred method for retrieving HTTP data is HttpUrlConnection. You might wanna check this blog post for details. You may also want to check the Javadoc for HttpUrlConnection
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
your problem may be the "strict mode" here.
you have to do http requests with a thread or an AsyncTask.
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
//http request here
//return the response as string
}
#Override
protected void onPostExecute(String result) {
//set the the data you get
}
then:
new RequestTask().execute(yourHttpRequestString)
Related
I am working on POST JSON data to server. It is working fine with a tutorial this link but it is not working with this with some of the required data changes. Is there anything related to Javaservlet and PHP links , as the first link is designed using Javasevlet and the other is in PHP ?
public static String POST(String url)
{
InputStream inputStream = null;
String result = "";
try {
org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
String json = "";
JSONObject jsonObject=new JSONObject();
/*JSONArray jsonArray=jsonObject.getJSONArray("object");
JSONObject jsonObject2=jsonArray.getJSONObject(10);*/
jsonObject.putOpt("id",2);
jsonObject.putOpt("address","myaddress");
json=jsonObject.toString();
StringEntity se=new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse=httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// person = new PersonLocator();
// person.setAddresS(myLocationText.getText().toString());
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
Thanks for the help in advance
I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.
I am uploading a file to server from my android application using the below code, and its working fine. now I want to pass a jsonobject also to servlet, I tried some way like
mpEntity.addPart("param",new StringBody(details.toString(),"text/plain",
Charset.forName("UTF-8")));
here the details is a JSON object, but its not working, so please help me to solve this.
this is my code(in android) for file uploading.
private class AsyncCaller extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
JSONObject obj=new JSONObject();
try {
obj.put("m1", "adad");
obj.put("m2", "adadad");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpPost httppost = new HttpPost(
"http://172.20.56.229:8084/AndroidTesting/UploadServlet");
File file = new File("/sdcard/CEA.txt");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFe = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFe);
httppost.setEntity(mpEntity);
System.out
.println("executing request " + httppost.getRequestLine());
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
httpclient.getConnectionManager().shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Why with first String the "jsonGetMethod" method works, but with second and third Strings - does not? When I'm inputting the URL from all the Strings in Android Web-Browser - I see the json response. (I'm using Eclipse, Real Android Device(not emulator) connected by Wi-Fi to internet, in the AndroidManifest Internet Permission is added.)
//This String works fine
private static String url = "http://json-ld.org/contexts/person.jsonld";
//Log.d(jsonStr) shows "null"
private static String url = "http://192.168.1.200:8080/test/json";
//Exception throws
private static String url = "192.168.1.200:8080/test/json";
public String jsonGetMethod(String url)
{
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
String jsonStr = jsonGetMethod(url);
Log.d(jsonStr);
I have noticed that my http requests tend to take alot of time compared apps communicating with same server. It makes my app feel sluggish and I was wondering if there is a better way of making these requests and updating the UI.
At the moment I use this method to make post requests
public String postRequest(List<NameValuePair> nameValuePairs, String method_name) {
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/"+method_name);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", "Basic somestuff");
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
result = rd.readLine();
return result;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
And in my UI thread (i.e my Fragment classes) I use this in an Async Task like this
class MakeRequest extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... counter) {
String result = "";
String method_name = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", value));
nameValuePairs.add(new BasicNameValuePair("name", name));
method_name = "petition/setPetition";
result = fixr.postRequest(nameValuePairs, method_name);
JSONObject jsonFile = new JSONObject(result);
if(!jsonFile.has("error")){
//Parse JSON using GSON
return "success";
}else{
return jsonFile.getString("error");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String jsonResult) {
try {
if(jsonResult != null){
//update UI
}else{
//Error message
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'd like to optimize this so users can have a really smooth experience on my application. I'm open to using third party http libraries or is there also an argument against using AysncTasks and maybe the runOnUiThread() instead.
Volley Library is better, http, https etc.
https://developers.google.com/live/shows/474338138
very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
Try Volley mate! I changed from AsyncTasks to Volley library and i am pretty pleased from the overall experience!
Volley Library