I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}
Related
I'm attempting to get a json string back from an HTTP post request in my andorid app. Using a solution from this post, code also shown here.
public void post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
httpClient.execute(httpPost);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I call post from inside of an Async Task (using to handle network access on a separate thread).
String result;
result = post("https://StringURLGoesHere.com/", "jsonStringBodyGoesHere");
According to the documentation for HttpClient class, to handle the response, I need to add a second parameter ResponseHandler to the HttpClient.execute() method.
public interface ResponseHandler<T> {
T handleResponse(HttpResponse var1) throws ClientProtocolException, IOException;
}
I did as such:
public String post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
ResponseHandler<String> reply = new ResponseHandler<String>() {
#Override
public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
return httpResponse.toString();
}
};
return httpClient.execute(httpPost,reply);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I show the string in a textview on my application. It reads:
org.apache.http.message.BasicHttpResponse#1446ef0c
or
org.apache.http.message.BasicHttpResponse#b83bd3d
or
org.apache.http.message.BasicHttpResponse#1c4c9e1d
and so on.
Why am I getting this return as a string? What should change in order to get the string of the json object returning after the post?
Try like below to capture HttpRepose to see your response;
HttpClient request = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
get.setHeader( "Authorization", token);
HttpResponse response = null;
try {
response = request.execute( get );
} catch ( ClientProtocolException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
StringBuffer result = new StringBuffer();
String line = "";
while ( (line = rd.readLine()) != null ) {
result.append( line );
}
System.out.println( response.getStatusLine().getStatusCode() );
System.out.println( result.toString() );
You could do like this:
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString; //this is your want
I am trying to use this method i also tried to impot libriries but all in vain. Kindly help me. Not any HTTPClient library is showing on my andriod studio. Help would be appreciated
public String getHttpPost(String url,ContentValues) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
Oh!Still you are using HttpClient.You can use HttpURLConnection,Volley etc. HttpClient class is now deprecated.Also add Internet permission, and dependensies in gradle file.
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(_url);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (_authenticationKey != null) {
urlConnection.setRequestProperty(_authenticationKey, _authenticationValue);
}
if (_jsonPacket != null) {
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(_jsonPacket);
wr.flush();
}
int statusCode = urlConnection.getResponseCode();
JSONObject job;
if (statusCode != HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.failureFromWebService, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + "Response code = " + statusCode);
}
} else {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.success, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + Constants.StringConstants.serverReadingResponseFailed);
}
}
You can use "Volley" library to make network call.
eg.
Add this line in build.gradle (Module:app)
compile 'com.mcxiaoke.volley:library:1.0.19'
As you are making network call you need internet permission. So add Internet permission line in Manifest.xml
Now you need to write a small method inside your class where you need to make network call and need to pass Hashmap to it. Hashmap contains all your post parameters.
private void getJSONResponse(HashMap<String, String> map, String url) {
pd.show();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Mayur", "Response : " + response);
//tv_res.setText(response.toString());
//pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
//tv_res.setText("ERROR");
//pd.dismiss();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));Volley.newRequestQueue(this).add(request);}
Now in your onCreate method or any other method just create a Hashmap of post parameters and pass it to this method with post url.
eg.
HashMap<String, String> map = new HashMap<String, String>();
map.put("fname", "Mayur");
map.put("lname", "Thakur");
getJSONResponse(map,<your url>);
I am new in android and java I want to get access data from this API.
All we need to do convert this into java code
curl --include --header "X-Access-Token: YOUR_API_TOKEN_HERE" "http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0"
Your given API has a header and basic GET format. This can be converted in Java easily.
See the code example,
public String httpGet(String s, String api_token) {
String url = s;
StringBuilder body = new StringBuilder();
httpclient = new DefaultHttpClient(); // create new httpClient
HttpGet httpGet = new HttpGet(url); // create new httpGet object
httpGet.setHeader("X-Access-Token", api_token);
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
}
Now call the function and pass the url along with your header API token,
httpGet("http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0", YOUR_API_TOKEN)
I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"
I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it?
I've tried with the methods offered by the HttpReponse class but didn't find it.
Thanks
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
You can modify your code like this:
//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//edit: there is already function for this
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
//Houston we have a problem
//we should do something with bad http status
return null;
}
EDIT: just one more thing ...
instead of requestToString(..); you can use EntityUtils.toString(..);
Have you tried this?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
Have you tried the following?
response.getStatusLine().getStatusCode()