Apache HttpClient get status code along with all redirection url - apache-httpclient-4.x

I want to get the status code of each redirected URL (with URL). I know there is a way through which we can get all redirection URLs by passing HttpClientContext but I want a status code as well. Is there any way to get a status code as well along with url?
var httpget = new HttpGet("www.dummy-url.com");
try (final var closeableHttpResponse = closeableHttpClient().execute(httpget, context);) {
final var instream = closeableHttpResponse.getEntity().getContent();
instream.close();
List<URI> redirectURIs = context.getRedirectLocations();
EntityUtils.consumeQuietly(closeableHttpResponse.getEntity());
}

Use a custom response interceptor to capture all incoming response messages
CloseableHttpClient httpclient = HttpClients.custom()
.addInterceptorLast(new HttpResponseInterceptor() {
#Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpClientContext clientContext = HttpClientContext.adapt(context);
RouteInfo route = clientContext.getHttpRoute();
HttpRequest request = clientContext.getRequest();
HttpHost targetHost = route.getTargetHost();
try {
URI uri = new URIBuilder(request.getRequestLine().getUri())
.setScheme(targetHost.getSchemeName())
.setHost(targetHost.getHostName())
.setPort(targetHost.getPort())
.build();
System.out.println(uri + " -> " + response.getStatusLine());
} catch (URISyntaxException ex) {
// unexpected. do some recovery
}
}
})
.build();
try {
HttpGet httpget = new HttpGet("http://google.com/");
httpclient.execute(httpget, new ResponseHandler<Void>() {
#Override
public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return null;
}
});
System.out.println("----------------------------------------");
} finally {
httpclient.close();
}
http://google.com:80/ -> HTTP/1.1 301 Moved Permanently
http://www.google.com:80/ -> HTTP/1.1 200 OK
----------------------------------------

Related

okhttp returns null response

```protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
ctx=getApplicationContext();
txtString= (TextView)findViewById(R.id.txtString);
httpClient = new OkHttpClient();
try {
sendGETT();
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void sendGETT() throws IOException {
httpClient = new OkHttpClient();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "my api key")
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.body().string());
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " +
responseHeaders.value(i));
Main3Activity.txtString.setText(response.header("Server"));
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.body().charStream());
final String prettyJsonString = gson.toJson(je);
runOnUiThread(new Runnable() {
#Override
public void run() {
txtString.setText(prettyJsonString);
}
});
}
}
});
}
}```
I'm trying to use okhttpclient with okhttp3, but it return a null value.i tried another url with headers which work fine but when i try this it gives null respone.I tried many solutions from net but I can't figured this out.hope for the help.thanks
This code works fine, for example,
for
Response response = client.newCall(request).execute();
Request request = new Request.Builder()
.url("https://httpbin.org/get")
.addHeader("custom-key", "mkyong") // add request headers
.addHeader("User-Agent", "OkHttp Bot")
.build();
or any other website but I want to get the content of website using rapid api with add headers
```Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "mine api for site")
.build();```

How do I send a HTTP request using OAUTH2 in Android?

I am trying to retrieve the data from my account by connecting to the Fitbit API. I have my app returning the Access Token I need to make the HTTP Request that returns the JSON but anything that I try, it returns an error. I have two Activities - MainActivity.java and TestActivity.java
In MainActivity.java I am simply opening a Chrome Custom Tab to direct the user to the Fitbit Authentication(Login) page. Once the user enters their details they are redirected back to the TestActivity.java as per the Fitbit API documentation. I am then printing the Acess Token which proves to me that it is connecting to the API.
What I need to do it make an HTTP request to returns the sleep data in JSON format. I know how to do it in Java but I am unsure how to do it in Android using the AsyncTask way. Any help is appreciated!
public class TestActivity extends AppCompatActivity {
String string;
String token;
#Override
protected void onNewIntent(Intent intent) {
string = intent.getDataString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
onNewIntent(getIntent());
//Toast.makeText(TestActivity.this, string , Toast.LENGTH_LONG).show();
Log.e("TAG", string);
Log.e("TAG", string.substring(string.indexOf("&access_token")+14));
token = string.substring(string.indexOf("&access_token")+14);
Context context = getApplicationContext();
Toast toast = Toast.makeText(context,"Access Token: "+ token,Toast.LENGTH_LONG );
Log.i("TAG", "Access Token: "+ token);
new JSONTask().execute("https://api.fitbit.com/1.2/user/-/sleep/date/2018-01-30.json");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try
{
URL url = new URL(params[0]);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) !=null)
{
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
Log.i("TAG", s);
}
}
I ended up having a breakthrough with this question. I figured out that I was extracting the Access Token incorrectly. So, instead of doing the following:
token = string.substring(string.indexOf("&access_token")+14);
I instead had to use this:
token = string.substring(string.indexOf("&access_token")+36,308);
The App was then able to make the necessary HTTP request to the Fitbit API which returned the JSON data that I needed.
One order of codes should be changed for preventing FC.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);

HTTP error 500 on Android

So here is my code, its purpose is to fecth a json file. I get an error 500 from the server, which means I know that it is an internal server error. As I can't access to the logs of the the server, I'm pretty much stuck from now... I read about session and cookies, maybe that's it. What do you guy think of it ?
private class ListingFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "ListingFetcher";
public static final String SERVER_URL = "http://www.myurl.com/listing.json";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Listing> events = new ArrayList<Listing>();
events = Arrays.asList(gson.fromJson(reader, Listing[].class));
content.close();
handlePostsList(events);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
My code is perfectly working. THe only mistake is on this line :
HttpPost post = new HttpPost(SERVER_URL);
Which should be
HttpGet get = new HttpGet(SERVER_URL);

how to handle http 400 and 401 error while using webclient to download JSON

I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}

Error : HTTP/1.1 302 Moved Temporarily

I am doing Http POST request using HTTPClient 4.2.2. I am using .pfx certificate to access the URL mentioned in post request. But I am getting 302, Move temporarily error
//Java Code
public class CertificateAuth {
private static final long TIMEOUT = 500000000L;
//set trust store to be used to trust server certificate
private String tokeApiPostUrl = "http://test.com/l1/rest1/lt/v1/data";
private String tokenPost = "{\"id\": \"Token_15555\",\"type\": \"token\",\"entity_type\": \"Store\",\"entity_id\": \"StoreId\",\"expiration_time\": 1376579410}";
//client is taken as class varibable so that Cookies set by Server persists between
//multiple calls
private HttpClient client = null;
public CertificateAuth() {
}
public String createToken() throws Exception {
// set reasonable timeouts as we seem to wait forever to get a response:
KeyStore keystore = KeyStore.getInstance("pkcs12");
InputStream keystoreInput = new FileInputStream("abc.pfx");
keystore.load(keystoreInput, "password".toCharArray());
SchemeRegistry schemeRegistry = new SchemeRegistry();
SSLSocketFactory lSchemeSocketFactory = new SSLSocketFactory(keystore, "qwerty10");
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", 443, lSchemeSocketFactory));
final HttpParams httpParams = new BasicHttpParams();
client = new DefaultHttpClient(new SingleClientConnManager(httpParams, schemeRegistry), httpParams);
String version = null;
HttpPost httpPost = new HttpPost(tokeApiPostUrl);
// httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
try {
Map<String, String> headersParameters = new HashMap<String, String>();
JSONObject jsonObj = new JSONObject(tokenPost);
setParametersJson(httpPost, headersParameters, jsonObj);
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
System.out.println("Succesfully queried");
}
} finally {
httpPost.releaseConnection();
}
return version;
}
private void setParametersJson(HttpRequestBase httpOperation, Map <String, String> headerParameters, JSONObject jsonObject) {
for (String headerName : headerParameters.keySet()) {
httpOperation.setHeader(headerName, headerParameters.get(headerName));
}
if (jsonObject != null) {
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
if (httpOperation instanceof HttpPost) {
((HttpPost) httpOperation).setEntity(stringEntity);
} else if (httpOperation instanceof HttpPut) {
((HttpPut) httpOperation).setEntity(stringEntity);
}
} catch(UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
CertificateAuth ua = new CertificateAuth();
ua.createToken();
}
}
Add this line to your code.
client.setRedirectStrategy(new LaxRedirectStrategy());