How to get error message when connect to server in Android - java

I use GET method to connect to the server, and the server responses http status code 403.
When I paste the url of my GET method to browser, I'm received "some text" and http status code 403. But when I send a GET request with the same url to the server by HttpURLConnection of Java(Android), I'm just received http status code 403, and response text is null.
So anyone can tell me how to get the "some text" when server return code 403.
Thanks in advance.

Just do as Zoombie wrote and add line:
String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
If it doesn't work, your server doesn't set the reason. Then you should map codes to standard reason phrases:
List of HTTP status codes

Try to use DefaultHttpClient class,
client = new DefaultHttpClient(httpParameters);
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}

Related

Issue with wsimport authentication when generating SOAP Java client

I use the following command to generate web service client files for java.
wsimport -keep http://test.com/test?wsdl -xauthfile auth.txt
The following was in auth.txt
http://user:password#ip:port//path
But, the password was having special characters like abcw#sdsds.
So I was getting wrong format error. So I have encoded password like abcw%40sdsds. But, now got authentication error due to wrong password because of parsing.
Is there any ways to handle this scenario ?
After checking online I found this bug was actually fixed in the latest version. But I still get the same issue. You can refer to the following links for information on the bug.
https://github.com/javaee/metro-jax-ws/issues/1101
So I finally made custom HTTP request with NTLM authentication using HTTP Client in Java.
String bodyAsString = ""; //Provide Input SOAP Message
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("UserName", "Password", "Host", "Domain"));
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
HttpPost post = new HttpPost("URL"); //Provide Request URL
try
{
StringEntity input = new StringEntity(bodyAsString);
input.setContentType("text/xml; charset=utf-8");
post.setEntity(input);
post.setHeader("Content-type", "text/xml; charset=utf-8");
post.setHeader("SOAPAction", ""); //Provide Soap action
org.apache.http.HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
return EntityUtils.toString(responseEntity);
}
}
I got the above solution from the following github link
https://github.com/sujithtw/soapwithntlm

HTTP post/API request works when sent from CURL on bash, fails from Apache http

I'm trying to use apache http components to interface with the Spotify api. The request I'm trying to send is detailed here under #1. When I send this request from bash using curl
curl -H "Authorization: Basic SOMETOKEN" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I get back a token like the website describes
However the following java code, which as far as I can tell executes the same request, gives back a 400 error
Code
String encoded = "SOMETOKEN";
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
URI auth = new URIBuilder()
.setScheme("https")
.setHost("accounts.spotify.com")
.setPath("/api/token")
.setParameter("grant_type", "client_credentials")
.build();
HttpPost post = new HttpPost(auth);
Header header = new BasicHeader("Authorization", "Basic " + encoded);
post.setHeader(header);
try {
response = client.execute(post);
response.getEntity().writeTo(System.out);
}
finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Error
{"error":"server_error","error_description":"Unexpected status: 400"}
The URI that the code prints is looks like this
https://accounts.spotify.com/api/token?grant_type=client_credentials
And the header looks like this
Authorization: Basic SOMETOKEN
Am I not constructing the request correctly? Or am I missing something else?
Use form url-encoding for the data in the body with the content-type application/x-www-form-urlencoded :
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("https://accounts.spotify.com/api/token");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
StringEntity data = new StringEntity("grant_type=client_credentials");
post.setEntity(data);
HttpResponse response = client.execute(post);

UTF-8 content Java request and PHP response

I send a request from a java code to php server then on server side I just echo what has received as response.
So in theory I will receive what I send. but I have problem on sending UTF-8 contents, when I send arabic characters I receive unexpected characters.
My java request code:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
String requestString = "سلام";
StringEntity entity = new StringEntity(requestString, "UTF-8");
entity.setContentType("application/json");
entity.setContentEncoding("UTF-8");
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setHeader("Accept-Charset", "utf-8");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpClient httpClient = new DefaultHttpClient(httpParams);
String responseString=null;
try
{
responseString = httpClient.execute(httpPost, responseHandler);
}
catch (IOException e)
{ e.printStackTrace(); }
My code on server side:
<?php
echo file_get_contents('php://input');
?>
In this test I send string "سلام" but in response I receive "سÙاÙ".
I also tried to solve the problem with changing charset with iconv(...) method on php but I failed.
I even don't know the problem is in client or server. Has anybody a help idea?
Answering to my own question:
In my case the problem was in server side. I changed the header of response of server and the problem solved:
header('Content-Type:application/json; charset=utf-8');

Android http post advanced request with body on hostmachine

I would like to do a HTTP post request from my virtual android device on the hostmachine.
Below you'll see an image on how I post, by using the old WebFetch tool.
I don't know what URL to use for calling the hostmachine?
I got no idea how my body string can be used an input?
Does anybody have an idea on how to solve this?
If you want to connect to the computer which is running the Android simulator, use the IP address 10.0.2.2. You can read more about it here.
Also check out the accepted answer in following question to see how json can be send as post data:
How to send POST request in JSON using HTTPClient?
you can use following code to make HTTP get request:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://10.0.2.2:port/your_path_with_parameter";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}

Getting Unexpected 401 from Apache HTTPClient Basic Auth

I'm attempting to do basic auth with Apache HTTPClient 4.x using the example from the site, the only change being that I've extracted some details out into constants, however I'm not getting the results I was hoping for.
Namely, with the logging turned up to debug, I'm getting: "DEBUG main client.DefaultHttpClient:1171 - Credentials not found", followed by a 401 error from the server.
I've manually validated that the credentials I've configured are correct, and the "Credentials not found" message leads me to believe the credentials were never passed in the request.
Any thoughts on what I might be doing wrong?
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(API_HOST, API_PORT),
new UsernamePasswordCredentials(API_USERNAME, API_PASSWORD));
HttpGet httpget = new HttpGet(API_TEST_URL);
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
Are you sure the AuthScope is set correctly? Try setting it like this just to see if the problem is there
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT)

Categories