Java applet HttpClient AccessControlException - java

I have created an applet which uses the HttpClient from Apache HTTP Components. The applet is supposed to open a remote webpage and print the source of the page to console. The code works fine when ran from IDE (NetBeans), however when deployed in a webpage it throws an AccessControlException:
access denied ("java.net.SocketPermission" "www.hardwarebase.net" "resolve")
Upon reading similar questions concerning the problem, it seemed like the problem was in the applet not being signed. I self-signed it, so when I ran it the next time, the applet asked for and got the permissions.
Still, I get the same exception. Here is the code of the main applet class:
public class MyApplet extends java.applet.Applet {
public DefaultHttpClient client;
public String useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1";
public void init()
{
resize(150,25);
client = new DefaultHttpClient();
String page = Get("http://www.hardwarebase.net"));
System.out.println(page);
}
public String Get(String url)
{
final HttpUriRequest request = new HttpGet(url);
request.setHeader("User-Agent", useragent);
HttpResponse response;
try {
response = (HttpResponse)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return client.execute(request);
} catch (IOException ex) {
Logger.getLogger(MyApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
);
return _getResponseBody(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String Post(String url, List<NameValuePair> nameValuePairs)
{
final HttpPost request = new HttpPost(url);
request.setHeader("User-Agent", useragent);
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
try {
response = (HttpResponse)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return client.execute(request);
} catch (IOException ex) {
Logger.getLogger(MyApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
);
return _getResponseBody(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public void paint(Graphics g)
{
g.drawString("Hello world!", 50, 25);
}
public String _getResponseBody(final HttpEntity entity) throws IOException, ParseException
{
if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
InputStream instream = entity.getContent();
if (instream == null) { return ""; }
if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); }
String charset = getContentCharSet(entity);
if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; }
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try
{
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1)
{
buffer.append(tmp, 0, l);
}
}
finally
{
reader.close();
}
return buffer.toString();
}
public String getContentCharSet(final HttpEntity entity) throws ParseException
{
if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
String charset = null;
if (entity.getContentType() != null)
{
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0)
{
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) { charset = param.getValue(); }
}
}
return charset;
}
}
How can I resolve this AccessControlException?

I have resolved the issue by switching from HttpClient to URLConnection. I am not sure why doesn't URLConnection throw the exception, while HttpClient does.

Related

HTTPClient ConnectionKeepAliveStrategy not working as expected

I have written the below code where I am sending XML content over a REST POST and then returning the response back to my calling function. I want my calling function to use the same connection for a defined time and should not create new connections again and again.
But this is not working as expected and its still creating new connections for every new request.
String out = null;
StringBuilder sb = new StringBuilder();
DefaultConnectionKeepAliveStrategy defaultConnectionKeepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1L)
keepAlive = 120000L;
return keepAlive;
}
};
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
HttpPost post = new HttpPost(url);
connectionManager.setMaxTotal(100);
connectionManager.setDefaultMaxPerRoute(100);
final int maxRetries = 3;
try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setRetryHandler((exception1, executionCount, context) -> {
try {
Thread.sleep(retryWaitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return (executionCount <= maxRetries);
}).setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
int waitPeriod = waitTime;
public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
this.waitPeriod *= 2;
return (executionCount <= maxRetries && response.getStatusLine().getStatusCode() >= 500);
}
public long getRetryInterval() {
return this.waitPeriod;
}
}).setKeepAliveStrategy(defaultConnectionKeepAliveStrategy).setConnectionTimeToLive(120L, TimeUnit.SECONDS).build()) {
try {
StringEntity requestEntity = new StringEntity(xml, ContentType.APPLICATION_XML);
post.setEntity(requestEntity);
CloseableHttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
} else {
.....
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
e.printStackTrace();
}
post.releaseConnection();
return out;
}
How can i improve the code?

ClascastException in linking JavaConnector in kony

I have created a simple java service in kony app.When i try to run the Test with input parameter i got the following exception.
java.lang.ClassCastException: com.kony.sample.KonyServerConnection cannot be cast to com.konylabs.middleware.common.JavaService
at com.konylabs.middleware.connectors.JavaConnector.execute(JavaConnector.java:142)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage.getJavaResponse(JavaServiceDefinitionEditorPage.java:1878)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage$InvokeJavaOperation.run(JavaServiceDefinitionEditorPage.java:1842)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
i followed this Link for reference
i have shared some of java code
private static final String URL = "http://serverurl/sendEmail?";
public static String getServerPersponce(String entitiy,String mHeader){
String responseBody = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
System.out.println("Requesting : " + httppost.getURI());
try {
StringEntity entity = new StringEntity(entitiy);
if(mHeader != null && !mHeader.equalsIgnoreCase(""))
httppost.addHeader("AuthToken" , mHeader);
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
InputStream stream = entity1.getContent();
responseBody = getStringFromInputStream(stream);
if (response.getStatusLine().getStatusCode() != 200) {
// responseBody will have the error response
}
//responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
public static void main(String[] args) throws Exception {
String data = "{\"CC\":[\"yuvarajag#gmail.com\"],\"Content\":\"sample string 2\",\"Subject\": \"sample string 1\",\"To\": [\"yuvarajag#gmail.com\",\"sakumarr#gmail.com\",]}";
String result = getServerPersponce(data, accessToken);
System.out.println("Result "+result);
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString().trim();
}
This java code is working fine. after creating a jar i included this jar to the Kony app.I am getting exception in kony java service integration.
In the code specified there is no implementation of com.konylabs.middleware.common.JavaService2 class. JavaService will work if you implement JavaService2 class in your class file and override its invoke meathod.
below is the sample:
public class <YOUR CLASS NAME> implements JavaService2 {
#Override
public Object invoke(String serviceId, Object[] arg1,
DataControllerRequest arg2, DataControllerResponse arg3)
throws Exception {
// YOUR LOGIC
return result;
}
}
Kony JavaConnector expects classes that implements JavaServer or JavaService2. Apparently com.kony.sample.KonyServerConnection does not implements them.

StringBuilder cannot append string

I'm using DefaultHttpClient to make a GET request from a URL.
Please see code bellow.
That you can see, if log the result with Log.i("result", l), when the loop finished, I can see full data of the response,
but if I use htmlResult = sb.toString(); I cannot get or see all data, maybe only a half of the response.
What is wrong here? Thanks for your comments.
Edit: i posted my code that everyone can help me:
public class DetailParser {
HTTPAsyncRequest _asyncRequest;
CompletionHandler _completion;
private String _currentURL;
private static DetailParser _instance;
public GadgetItem _currentItem;
static InputStream _inputStream = null;
public static DetailParser getInstance()
{
if(_instance == null)
_instance = new DetailParser();
return _instance;
}
public class HTTPAsyncRequest extends AsyncTask<String, Integer, Response>
{
#Override
protected Response doInBackground(String... params) {
_currentURL = params[0];
String result = getData(params[0]);
Response response = new Response(result, params[0]);
return response;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Response response) {
if(response == null)
return;
if(!_currentURL.equals(response.urlRequest))
{
super.onPostExecute(response);
}
else
{
// TODO Auto-generated method stub
parseGadgetItem(response.xmlResult);
if(_completion != null)
_completion.getDescriptionDone(_currentItem);
super.onPostExecute(response);
}
}
public String getData(String url)
{
private String _resultHTML = null;
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
_inputStream = httpEntity.getContent();
reader = new BufferedReader(new InputStreamReader(_inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String l = "";
String nl = System.getProperty("line.separator");
while ((l = reader.readLine()) != null) {
sb.append(l + nl);
// Log.i("result", l);
// htmlResult += l + nl;
}
_resultHTML = sb.toString();
// Log.i("Result", _resultHTML);
// htmlResult = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
Log.e("GetMethodEx", e.getMessage());
}
}
return _resultHTML;
}
}
// constructor
public DetailParser() {
}
private void abortRequest()
{
if(_asyncRequest != null)
_asyncRequest.cancel(true);
}
public void getGadgetDescription(GadgetItem item, final CompletionHandler completion)
{
_currentItem = item;
_completion = completion;
abortRequest();
_asyncRequest = (HTTPAsyncRequest) new HTTPAsyncRequest().execute(item.gadget_link,null,null);
}
public void parseGadgetItem(String html) {
// HERE : data is missing
if (xml == null)
return;
try {
Document doc = Jsoup.parse(html);
Elements e = doc.getElementsByClass("thecontent entry-content");
//
} catch (Exception e) {
}
}
}
Try this:
Declare this globally
static InputStream re = null;
private String result = null;
Now use this code in your class
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response1;
try {
response1 = client.execute(httpGet);
Log.e("Refresh is: ", response1.toString());
HttpEntity entity = response1.getEntity();
re=entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(re, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String result= sb.toString();
System.out.println(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Android GET and POST Request

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.
Thanks.
You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
String post = "this will be the post data that you will send"
request.setDoOutput(true);
request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
request.setMethod("POST");
request.connect();
OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
writer.write(post);
writer.flush();
}
}
A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
request.setMethod("GET");
request.connect();
}
}
I prefer using dedicated class to do GET/POST and any HTTP connections or requests.
Moreover I use HttpClient to execute these GET/POST methods.
Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager.
There is an example of using GET (fetchData) and POST (sendOrder)
As you can see execute is general method for executing HttpUriRequest - it can be POST or GET.
public final class ClientHttpClient {
private static DefaultHttpClient client;
private static CookieStore cookieStore;
private static HttpContext httpContext;
static {
cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
client = getThreadSafeClient();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
client.setParams(params);
}
private static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
params);
return client;
}
private ClientHttpClient() {
}
public static String execute(HttpUriRequest http) throws IOException {
BufferedReader reader = null;
try {
StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(http, httpContext);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new BufferedReader(new InputStreamReader(content, CHARSET));
String line = null;
while((line = reader.readLine()) != null) {
builder.append(line);
}
if(statusCode != 200) {
throw new IOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
+ ", " + builder.toString());
}
return builder.toString();
}
finally {
if(reader != null) {
reader.close();
}
}
}
public static List<OverlayItem> fetchData(Info info) throws JSONException, IOException {
List<OverlayItem> out = new LinkedList<OverlayItem>();
HttpGet request = buildFetchHttp(info);
String json = execute(request);
if(json.trim().length() <= 2) {
return out;
}
try {
JSONObject responseJSON = new JSONObject(json);
if(responseJSON.has("auth_error")) {
throw new IOException("auth_error");
}
}
catch(JSONException e) {
//ok there was no error, because response is JSONArray - not JSONObject
}
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject chunk = jsonArray.getJSONObject(i);
ChunkParser parser = new ChunkParser(chunk);
if(!parser.hasErrors()) {
out.add(parser.parse());
}
}
return out;
}
private static HttpGet buildFetchHttp(Info info) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(FETCH_TAXIS_URL);
builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
HttpGet get = new HttpGet(builder.toString());
return get;
}
public static int sendOrder(OrderInfo info) throws IOException {
HttpPost post = new HttpPost(SEND_ORDER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "" + info.getTaxi().getId()));
nameValuePairs.add(new BasicNameValuePair("address", info.getAddressText()));
nameValuePairs.add(new BasicNameValuePair("name", info.getName()));
nameValuePairs.add(new BasicNameValuePair("surname", info.getSurname()));
nameValuePairs.add(new BasicNameValuePair("phone", info.getPhoneNumber()));
nameValuePairs.add(new BasicNameValuePair("passengers", "" + info.getPassengers()));
nameValuePairs.add(new BasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
nameValuePairs.add(new BasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
nameValuePairs.add(new BasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = execute(post);
if(response == null || response.trim().length() == 0) {
throw new IOException("sendOrder_response_empty");
}
try {
JSONObject json = new JSONObject(response);
int orderId = json.getInt("orderId");
return orderId;
}
catch(JSONException e) {
throw new IOException("sendOrder_parsing: " + response);
}
}
EDIT
The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.
If you have URL object you can pass to execute method:
HttpGet request = new HttpGet(url.toString());
execute(request);
As you said: the GET-Parameters are in the URL - So you can use a loadUrl() on your Webview to send them.
[..].loadUrl("http://www.example.com/data.php?param1=value1&param2=value2&...");
The developer training docs have a good example on GET requests. You're responsible for adding the query parameters to the URL.
Post is similar, but as you said, quite different. The HttpConnectionURLConnection class can do both, and it's easy to just set the post body with an output stream.
protected String doInBackground(String... strings) {
String response = null;
String data = null;
try {
data = URLEncoder.encode("CustomerEmail", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = Constant.URL_FORGOT_PASSWORD;// this is url
response = ServiceHandler.postData(url,data);
if (response.equals("")){
return response;
}else {
return response;
}
}
public static String postData(String urlpath,String data){
String text = "";
BufferedReader reader=null;
try
{
// Defined URL where to send data
URL url = new URL(urlpath);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
return text;
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return text;
}
private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.file = file;
this.fileName = fileName;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isProgressVisible) {
showProgressDialog();
}
}
#Override
protected String doInBackground(Void... params) {
try {
if (Utils.isInternetAvailable(context)) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(20, TimeUnit.SECONDS);
OkHttpClient client = clientBuilder.build();
if (reqMethod == RequestMethod.GET) {
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String message = response.message();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", message);
return jObj.toString();
} else if (reqMethod == RequestMethod.POST) {
FormBody.Builder formBuilder = new FormBody.Builder();
RequestBody body = formBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
} else if (reqMethod == RequestMethod.MULTIPART) {
MediaType MEDIA_TYPE = fileName.endsWith("png") ?
MediaType.parse("image/png") : MediaType.parse("image/jpeg");
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));
RequestBody body = multipartBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
}
} else {
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 0);
jObj.put("response", context.getString(R.string.no_internet));
return jObj.toString();
}
} catch (final Exception e) {
e.printStackTrace();
JSONObject jObj = new JSONObject();
try {
jObj.put("statusCode", 0);
jObj.put("response", e.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
return jObj.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObj = new JSONObject(result);
if (jObj.getInt("statusCode") == 1) {
listener.onSuccess(requestId, jObj.getString("response"));
} else {
listener.onError(requestId, jObj.getString("response"));
}
} catch (Exception e) {
listener.onError(requestId, result);
} finally {
dismissProgressDialog();
}
}
private void showProgressDialog() {
progressDialog = new MyProgressDialog(context);
}
private void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;
private NetworkManager() {
arrRequestListeners = new HashSet<>();
arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}
public static NetworkManager getInstance() {
if (instance == null)
instance = new NetworkManager();
return instance;
}
public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public void isProgressBarVisible(boolean isProgressVisible) {
this.isProgressVisible = isProgressVisible;
}
public void setListener(RequestListener listener) {
try {
if (listener != null && !arrRequestListeners.contains(listener)) {
arrRequestListeners.add(listener);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSuccess(int id, String response) {
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (RequestListener listener : arrRequestListeners) {
if (listener != null)
listener.onSuccess(id, response);
}
}
}
#Override
public void onError(int id, String message) {
try {
if (Looper.myLooper() == null) {
Looper.prepare();
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (final RequestListener listener : arrRequestListeners) {
if (listener != null) {
listener.onError(id, message);
}
}
}
}
public void removeListener(RequestListener listener) {
try {
arrRequestListeners.remove(listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Create RequestListner intreface
public void onSuccess(int id, String response);
public void onError(int id, String message);
Get Unique Number
private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();
private AtomicInteger seq;
private UniqueNumberUtils() {
seq = new AtomicInteger(0);
}
public int getUniqueId() {
return seq.incrementAndGet();
}
public static UniqueNumberUtils getInstance() {
return INSTANCE;
}

How can I send HTTP Basic Authentication headers in Android?

I am not sure how to send HTTP Auth headers.
I have the following HttpClient to get requests, but not sure how I can send requests?
public class RestClient extends AsyncTask<String, Void, JSONObject> {
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
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();
}
/*
* This is a test function which will connects to a given rest service
* and prints it's response to Android Log with labels "Praeda".
*/
public JSONObject connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json) {
}
}
This is covered in the HttpClient documentation and in their sample code.
Maybe the documentation of HttpClient can help: link
Since Android compiles HttpClient 4.0.x instead of 3.x, below snippet is for your reference.
if (authState.getAuthScheme() == null) {
AuthScope authScope = new Au HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);thScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(preemptiveAuth, 0);

Categories

Resources