Android: How get the status-code of an HttpClient request - android

I want to download a file and need to check the response status code (ie HTTP /1.1 200 OK).
This is a snipped of my code:
HttpGet httpRequest = new HttpGet(myUri);
HttpEntity httpEntity = null;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
...
How do i get the status-code of the response?

This will return the int value:
response.getStatusLine().getStatusCode()

if (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK){
...
}

Use code() function of response to get its HTTP code:
val code = response.code()

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

get the HTTP status server

Hi I am developing an android application, I like to create a class to get the HTTP status before send the data to the server with HTTP Post.
Have any form to get the HTTP status of this server?
I read to get the 200 code is the server is running and another code no
Thanks.
Resolved the timeout is very long, My solution is:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpclient = new DefaultHttpClient(params);
and then:
HttpGet httpRequest = new HttpGet(server);
HttpResponse response = httpclient.execute(httpRequest);
You could do the following
HttpGet httpRequest = new HttpGet(myUri);
HttpEntity httpEntity = null;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
response.getStatusLine().getStatusCode()
This is how you get Response code if you are using HttpUrlConnection :
when server is not running
int status = ((HttpURLConnection) connection).getResponseCode();
Log.i("", "Status : " + status);
And here is if you are using HttpClient :
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());

Android : call httpget with redirect_uri

I want to make httpget request by android application,
URL = https://www.facebook.com/dialog/oauth?client_id=<number>&redirect_uri=<SOME_URL>&scope=email
Above URL is working fine with browser, It give me proper result on server side, but when I am making http call from application it won't work, got the 200 Response, but it won't give me result.
Code snippet:
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams,
CONN_TIMEOUT);
HttpGet httpGet = new HttpGet(URL);
Log.d(TAG,"URL :"+ httpGet.getURI().toURL().toString());
DefaultHttpClient client = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = client.execute(httpGet);
//Log.d(TAG,"httpResponse :" +EntityUtils.toString(httpResponse.getEntity()));
res = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Response : " + res);
this is because
200 response code "OK"
The request has succeeded. The information returned with the response is dependent on the method used in the request,if there is some result request code will 204

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

How can I read a bytearray from an HttpResponse?

I'm making an http connection using following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = client.execute(httpPost);
I want to read a bytearray from the response object.
How would I do that?
You can read the byte array directly with the method: EntityUtils.toByteArray
Example
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("localhost:8080/myurl");
HttpResponse response = client.execute(get);
byte[] content = EntityUtils.toByteArray(response.getEntity());
You can use:
HttpResponse response = client.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
byte[] bytes = content.getBytes("UTF8");
You can replace the character encoding with one appropriate for the response.
I did something very similar to this, but it was a while ago.
Looking at my source code I used
HttpClient client = new DefaultHttpClient();
String url = "http://192.168.1.69:8888/sdroidmarshal";
HttpGet getRequest = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String proto = client.execute(getRequest, responseHandler);
I'm pretty certain that the ResponseHandler is the key to this. My get request simply returned something I needed as a string, which was quite simple.
In the case of a bytearray you'll probably want to use an InputStream like so
ResponseHandler<InputStream> responseHandler = new BasicResponseHandler();
InputStream in = client.execute(getRequest, responseHandler);
After which just handle the InputStream as normal.
A bit of googling suggested you may also need to use HttpResponseHandler() rather than BasicResponseHandler() as in my example, I'd fiddle.
The full source code of my work is here, it might be helpful for you.
Kotlin Way
run this on async task on background thread otherwise it will through the error that network task is running on main thread
doAsync {
val client: HttpClient = DefaultHttpClient()
val get = HttpPost("*your url*")
get.setHeader("Authorization","Bearer "+Utils.token)
val response: HttpResponse = client.execute(get)
val content = EntityUtils.toByteArray(response.getEntity())
onComplete {
createPdf(content)
}
}

Categories

Resources