NetworkOnMainThreadException sometimes thrown - java

I try to get response from POST request. The problem is that sometimes I get NetworkOnMainThreadException although I'm using AsyncTask for the network communication. That means that sometimes I get the response successfully, and sometimes I get this exception.
Here is my HTTP POST request AsyncTask:
static class HTTPPostRequest extends AsyncTask<PostRequestParams, Void, AsyncResponse> {
#Override
protected AsyncResponse doInBackground(PostRequestParams... params) {
AsyncResponse retVal = new AsyncResponse();
HttpClient client = getHttpClient();
UrlEncodedFormEntity formEntity = null;
HttpPost request = new HttpPost();
try {
request.setURI(new URI(params[0].URL));
formEntity = new UrlEncodedFormEntity(params[0].params);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
retVal.setOutput(response);
} catch (ClientProtocolException e) {
retVal.setException(e);
} catch (IOException e) {
retVal.setException(e);
} catch (URISyntaxException e) {
retVal.setException(e);
}
return retVal;
}
}
And the code that actually call it:
AsyncResponse response = new AsyncResponse();
PostRequestParams postParams = new PostRequestParams();
postParams.URL = URL + "login.php";
postParams.params.add(new BasicNameValuePair("username", username));
postParams.params.add(new BasicNameValuePair("password", password));
try {
response = new HTTPPostRequest().execute(postParams).get();
if (response.getException() != null) {
return "Error";
}
HttpResponse httpResponse = (HttpResponse) response.getOutput();
if (httpResponse.getStatusLine().getStatusCode() != 200) {
return "Error " + httpResponse.getStatusLine().getStatusCode();
}
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
} catch (InterruptedException | ExecutionException | IllegalStateException | IOException e) {
response.setException(e);
return null;
}

You should move the code that handles the InputStream, like:
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
to your AsyncTask as well. Handling InputStreams is nothing that you want to do in your UI Thread.

Related

Unable to post JSON data using HttpPost

I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"

Retrieve get response with Android

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? -.-"

Java HTTP-Request with POST-Data

I wrote the following code in java to send some data via POST-Variables to a PHP-File of my website and then I want to get the source code of this website.
public DatabaseRequest(String url, IDatabaseCallback db_cb)
{
this.db_cb = db_cb;
site_url = url;
client = new DefaultHttpClient();
request = new HttpPost(site_url);
responseHandler = new BasicResponseHandler();
nameValuePairs = new ArrayList<NameValuePair>(0);
}
public void addParameter(List<NameValuePair> newNameValuePairs)
{
nameValuePairs = newNameValuePairs;
}
public void run()
{
db_cb.databaseFinish(getContent());
}
public String[] getContent()
{
String result = "";
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
result = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] result_arr = result.trim().split("<br>");
for (int i = 0; i < result_arr.length; i++)
{
result_arr[i] = result_arr[i].trim();
}
return result_arr;
}
When I want to run this code, then eclipse throws the following error message:
Try this:
// executes the request and gets the response.
HttpResponse response = client.execute(httpPostRequest);
// get the status code--- 200 = Http.OK
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity httpEntity = response.getEntity();
responseBody = httpEntity.getContent();
if (statusCode = 200) {
// process the responseBody.
}
else{
// there is some error in responsebody
}
EDIT: To handle UnsupportedEncodingException
Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.
// Url Encoding the POST parameters
try {
httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}

HttpClient.excute(HttpPost) no response

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

How can I send HTTP Basic Authentication headers in Android?

I am not sure how to send HTTP Auth headers.
I have the following HttpClient to get requests, but not sure how I can send requests?
public class RestClient extends AsyncTask<String, Void, JSONObject> {
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
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();
}
/*
* This is a test function which will connects to a given rest service
* and prints it's response to Android Log with labels "Praeda".
*/
public JSONObject connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json) {
}
}
This is covered in the HttpClient documentation and in their sample code.
Maybe the documentation of HttpClient can help: link
Since Android compiles HttpClient 4.0.x instead of 3.x, below snippet is for your reference.
if (authState.getAuthScheme() == null) {
AuthScope authScope = new Au HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);thScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(preemptiveAuth, 0);

Categories

Resources