I want to know how to keep refreshing token every 30 min. Currently i dont have it. I need to cache that token for 30 min and then replace current token with the new refresh token.
Right now when i pass 1000 records all records uses same Auth token but the program runs more than 1 hour. I get Auth token expired error for some of the records.
Can anyone help me with how to handle that scenario ?
Thanks in advance
This is call class and will be calling token class.
package main.java.com.test;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import com.google.common.base.Stopwatch;
public class Call {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException
{
new Call().execute();
}
public String execute() throws IOException {
String number = "01";
String id = "0123456789";
String cd = "107BC0000X";
Token getToken = new Token();
String token = null;
try {
token = getToken.Token();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("access token" + token);
return token;
}
}
This is another class called Token
package main.java.com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jettison.json.JSONObject;
public class Token {
private final String USER_AGENT = "Mozilla/5.0";
public String Token() throws Exception
{
Token http = new Token();
http.sendGet();
String token = http.sendPost();
return token;
}
private String sendPost() throws Exception
{
String url = "https://YOUR_AUTH0_DOMAIN/oauth/token";
HttpClient client = new DefaultHttpClient();
HttpClient httpClient1 = wrapClient(client);
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent" , "Mozilla/5.0");
List urlParam = (List) new ArrayList();
urlParam.add(new BasicNameValuePair("client_id", ""));
urlParam.add(new BasicNameValuePair("grant_type", ""));
urlParam.add(new BasicNameValuePair("client_secret", ""));
post.setEntity(new UrlEncodedFormEntity(urlParam));
HttpResponse response = httpClient1.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null){
result.append(line);
}
String[] JsonTags0 = result.toString().split(",");
String[] JsonTags1 = result.toString().split(":");
String token1 = JsonTags1[1].trim();
return token1.substring(1,37);
}
private void sendGet()
{
}
public static HttpClient wrapClient(HttpClient base)
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager1();
ctx.init(null, new TrustManager[] {tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ClientConnectionManager ccm = base.getConnectionManager(ctx , SSLSocketFactory , ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf , 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}
Related
I'm trying to send https post request to my api that send json response, this is a search function so it will require 1 parameter, but i cannot get the expected result from my api, here are my code
Handler.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class Handler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Handler(){
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params2 = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params2, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params2);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error : " + e.toString());
}
return response;
}
makeServiceCall is used to make the request to url, but it only works with GET request and couldnt work with POST request, how do i fix this?
I'm trying to run a plugin that makes HTTP/HTTPS POST requests. On it its declared the needed dependencies, that is httpclient and httpcore. I'm using versions 4.5.3 and 4.4.6 respectively. Although imported correctly all (I mean), I got this error on execution time:
Caused by: java.lang.NoClassDefFoundError:
org/apache/http/ssl/TrustStrategy
25.06 19:59:12 [Server] INFO at
com.b5team.postrequest.Main.onCommand(Main.java:77) ~[?:?]
25.06 19:59:12 [Server] INFO at
org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~
[Spigot.jar:git-Spigot-3fb9445-6e3cec8]
25.06 19:59:12 [Server] INFO ... 10 more
25.06 19:59:12 [Server] INFO Caused by:
java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy
And here is my code:
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
public class SocketPOSTRequest {
public void sendRequest(String myurl, String hash, String args[]) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {
HttpClientBuilder b = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
HttpClient client = b.build();
HttpPost post = new HttpPost(myurl);
List<NameValuePair> params = new ArrayList<NameValuePair>(args.length);
params.add(new BasicNameValuePair("hash", hash));
for(int i = 0; i < args.length; i++) {
params.add(new BasicNameValuePair("arg"+i, args[i]));
}
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
}
}
}
EDIT: I'm using Ant to build, and the dependencies are correctly added. I tested too with Maven, adding the dependencies, but the error remains.
EDIT2: Switched to Maven, added maven-shade-plugin and maven-compile-plugin. The error disappeared, but now got this java.lang.NoSuchMethodError: org.apache.http.impl.client.HttpClientBuilder.setSSLContext. When running with junit, don't occurs any errors. It only occurs when running on server, that is Spigot 1.11.2 Minecraft Server.
if you are using a maven project, add the below dependency in your pom.xml file.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
So, I replaced the sslcontext methods from apache httpclient and httpcore with javax sslcontext methods. Now, everything works fine. Remembering, that the above code was working normally on pure java. The real problem was when running on Minecraft server.
Anyway, i will put below the new code, for documentation, maybe helps someone.
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsPOSTRequest {
public static void sendRequest(String myurl, String hash, String args[]) throws NoSuchAlgorithmException, KeyManagementException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(context);
URL url = new URL(myurl);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
ArrayList<String> params = new ArrayList<String>(args.length + 1);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("hash=" + hash);
for(int i = 0; i < params.size(); i++) {
output.writeBytes("&");
output.writeBytes("arg" + i + "=" + args[i]);
output.flush();
}
output.flush();
output.close();
DataInputStream input = new DataInputStream(con.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
System.out.println("[POSTRequest] Resp Code:"+con.getResponseCode());
System.out.println("[POSTRequest] Resp Message:"+con.getResponseMessage());
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
input.close();
} catch (UnsupportedEncodingException e) {
System.out.println("[POSTRequest] Encoding error. Maybe string have invalid caracters.");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("[POSTRequest] Invalid URL. Verify your URL and try again.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("[POSTRequest] Error on HTTPS connection.");
e.printStackTrace();
}
}
private static class DefaultTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
I'm new to Android and Java. I'm creating an app to login to my ISP. This is the page: http://reliancebroadband.co.in/reliance/login.do
Earlier, I was using a python script, which worked flawlessly. Its like this:
#!/usr/bin/env python
# encoding: utf-8
import urllib2, urllib, cookielib
username = 'my-username'
password = 'my-password'
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
response = opener.open("http://reliancebroadband.co.in/reliance/startportal_isg.do")
login_data = urllib.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'})
resp = opener.open('http://reliancebroadband.co.in/reliance/login.do', login_data)
And now i'm trying to create an android app(source: http://www.compiletimeerror.com/2013/01/login-application-for-android.html#.U7AFBPmSz9Y) (Tried contacting the developer there, but he's not responding.)
The app is compiling correctly, but while tring to login, its just returning the source code of the login page in the error dialogue, instead of logging in.
Here's the code:
MainActivity.java:
package com.app.reliancebblogin;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity
{
EditText un, pw;
TextView error;
Button ok;
private String resp;
private String errorMsg;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_un);
pw = (EditText) findViewById(R.id.et_pw);
ok = (Button) findViewById(R.id.btn_login);
error = (TextView) findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable()
{
#Override
public void run()
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost("http://reliancebroadband.co.in/reliance/login.do", postParameters);
String res = response.toString();
resp = res.replaceAll("\\s+", "");
}
catch (Exception e)
{
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try
{
/** wait a second to get response from server */
Thread.sleep(1000);
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty())
{
error.setText(errorMsg);
}
}
catch (Exception e)
{
error.setText(e.getMessage());
}
}
});
}
}
SimpleHttpClient.java:
package com.app.reliancebblogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient
{
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
I'm following this tutorial :
http://www.tutos-android.com/importer-ajouter-certificat-ssl-auto-signe-bouncy-castle-android/comment-page-2#comment-2159
(SSl auto signed certificate problem)
JsonParserFUnction code :
package com.example.androidsupervision;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class JsonReaderPost {
public JsonReaderPost() {
}
public void Reader() throws IOException, JSONException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
String ints = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query","SELECT+AlertId+FROM+Orion.Alerts"));
//HttpClient client = new DefaultHttpClient();
**//Here is the problem**
HttpClient client =new MyHttpClient(getApplicationContext());
HttpPost httpPost = new
HttpPost("https://192.168.56.101:17778/SolarWinds/InformationService/v3/Json/Query");
httpPost.addHeader("content-type", "application/json");
httpPost.addHeader("Authorization", "Basic YWRtaW46");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response;
String result = null;
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
// System.out.println("RESPONSE: " + result);
Log.e("Result", "RESPONSE: " + result);
instream.close();
}
// Converting the String result into JSONObject jsonObj and then into
// JSONArray to get data
JSONObject jsonObj = new JSONObject(result);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject r = results.getJSONObject(i);
ints = r.getString("AlertId");
Log.e("Final Result", "RESPONSE: " + ints);
}
}
public static String convertStreamToString(InputStream is) {
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();
}
}
I get in this line an error :
HttpClient client =new MyHttpClient(getApplicationContext());
The error is : The method getApplicationContext() is undefined for the type JsonReaderPost
You should send the context of your activity when you instantiate the class:
private Context mContext;
public JsonReaderPost(Context mContext) {
this.mContext = mContext;
}
Then, you should use "mContext" instead of getApplicationContext();
It is unknown because your class doesn't extend any other Class that has a Context, so it doesn't know what that method is. Such is, for example, an Activity.
However, using getApplicationContext(), unless you really know what you're doing, is almost always wrong. This will bring undesired behaviors like Exceptions when handled not properly. You should always use the Context of the class you're handling.
You can know which classes implement Context and get more info on contexts here.
My code works for http, but not https. Here is the error message im getting when i call getMessage() on the IOException:
java.net.SocketException: Address family not supported by protocol
heres my code:
package com.evankimia;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class XMLParserTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Log.e("sys",""+getXML());
}
}
public String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = this.createHttpClient();
HttpPost httpPost = new HttpPost("https://web2.uconn.edu/driver/old/timepoints.php?stopid=10");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Cans't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Cand't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
e.getMessage();
}
return line;
}
private DefaultHttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
}
The method you listed only works for http. Make your program identify https url and use some thign like following.
/**
* Initialize the HTTP/S connection (if needed)
*
* #param keystoreFile the full path of the keystore file
* #param keystorePass the password for the keystore file
*/
private void initHttps(String keystoreFile, String keystorePass)
{
// check if the URL uses HTTP/S
if (url.toLowerCase().startsWith(HTTPS_PROTOCOL))
{
print("Initializing HTTP/S protocol...");
// set the system properties needed for HTTP/S
System.setProperty("javax.net.ssl.keyStore", keystoreFile);
System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", keystoreFile);
System.setProperty("javax.net.ssl.trustStorePassword", keystorePass);
System.setProperty("javax.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
//int addProvider = Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{ // fix a HTTP/S handshake issue
public boolean verify(String hostName, SSLSession session)
{ // Verify that the host name is acceptable
return true;
}
});
}
}