Android: Making Https Request

Android - Sending HTTPS Get Request

You should be getting a compile error.

This is the correct version:

HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy="));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;

Therefore now if you have an error your response will be returned as null.

Once you have the response and checked it for null, you'll want to get the content (i.e. your JSON).

http://developer.android.com/reference/org/apache/http/HttpResponse.html
http://developer.android.com/reference/org/apache/http/HttpEntity.html
http://developer.android.com/reference/java/io/InputStream.html

response.getEntity().getContent();

This gives you an InputStream to work with. If you want to convert this to a string you'd do the below or equivalent:

http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/

public static String convertStreamToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
Writer writer = new StringWriter();

char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}

When you have this string you need to create a JSONObject from it:

http://developer.android.com/reference/org/json/JSONObject.html

JSONObject json = new JSONObject(inputStreamAsString);

Done!

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

  • Retrofit
  • OkHttp
  • Volley
  • HttpUrlConnection

Original Answer

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

Easy android https request?

The best library I know so far for network requests is Retrofit. It's kind of a standard for Android apps. If you want something more low level you can use Okhttp.

Both libraries can work together, and they are more than production ready. Of course, they support https and many other security features as ssl certificate pinning.

They support running the request on the same thread you are or in a background queue provided by the library, up to you if then you want to wrap it on an asyncTask, simple thread or service, those libraries leave you some freedom in that matter.

How can I make a simple HTTP request in MainActivity.java? (Android Studio)

You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.

Android force this behaviour by throwing an exception if you use the HttpUrlConnection object from the main thread.

You should then make your network request in the background, and then update the UI on the main thread. The AsyncTask class can be very handy for this use case !

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}

protected void onProgressUpdate(Integer... progress) {
}

protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}

And you start this process this way:

new GetUrlContentTask().execute(sUrl)

Android: Making Https Request

This method takes an HttpClient instance and returns a ready-for-https HttpClient instance.

 private HttpClient sslClient(HttpClient client) {
try {
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new MySSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, client.getParams());
} catch (Exception ex) {
return null;
}
}

Because the Android org.apache.http.conn.ssl.SSLSocketFactory does not have the SSLSocketFactory(SSLContext) constructor, I have extended the class as follows.

 public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

sslContext.init(null, new TrustManager[] { tm }, null);
}

public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}

@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

Excellent article here: http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html

And some help here: Trusting all certificates using HttpClient over HTTPS

Flutter released app is not supporting http ( not https ) request in android version 10

add android:usesCleartextTraffic="true"to AndroidManifest.xml

androidmanifest.xml

then follow this step:

  1. stop your app
  2. flutter clean
  3. flutter pub get
  4. run your app again

it solves my problem a few days ago.



Related Topics



Leave a reply



Submit