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);
Related
I'm making a request to my server, but the response is given in String, and I need to get data from there, for example, the if response: {"response":{"balance":85976,"adres":"pasaharpsuk#gmail.com"}}
and need to get a balance
CODE:
public class test {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// Создать запрос на получение
HttpGet httpGet = new HttpGet("http://localhost:8080/api/bank/my_wallet");
httpGet.setHeader("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwYXNhaGFycHN1a0BnbWFpbC5jb20iLCJyb2xlIjoiVVNFUiIsImlhdCI6MTY1MjUzNzQ3NSwiZXhwIjoxNjUzNTM3NDc1fQ.zYQqgXA0aeZAMm7JGhv4gOQEtks2iyQqGoqOOrdxy5g");
// модель ответа
CloseableHttpResponse response = null;
try {
// Выполнить (отправить) запрос Get от клиента
response = httpClient.execute(httpGet);
// Получить объект ответа из модели ответа
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println(EntityUtils.toString(responseEntity));
}
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
// освободить ресурсы
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
'''
All you need is a JSON parser for the entity after checking the content type header. https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html#getContentType()
For example you can use JSONObject from org.json to convert string to json. https://developer.android.com/reference/org/json/JSONObject#JSONObject(java.lang.String)
JSONObject o = new JSONObject(EntityUtils.toString(responseEntity));
I have written this piece of code for sending the POST request to a localhost server running nodejs having a certificate generated using openssl command. But when I am trying to send the post request, I can see in android log the issue with the trust anchor and POST request on https is not working but is working if I remove the certificate from nodejs server and send request with http. I know this is because my certificate is not verified from any well known CA like verisign. So, how can I send the request to this https server? I also tried installing the certificate in my android phone but it didn't solved my problem either. I can post the source code of HttpClient.java as well.
public class MainActivity extends AppCompatActivity {
Button encAndSendBtn;
TextView companyName, modelNumber, specification;
public MainActivity() throws MalformedURLException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
encAndSendBtn = (Button) findViewById(R.id.encAndSend);
companyName = (TextView) findViewById(R.id.company);
modelNumber = (TextView) findViewById(R.id.modNum);
specification = (TextView) findViewById(R.id.spec);
}
public void onclickbutton(View view) {
encSend scv = new encSend();
scv.execute();
}
private class encSend extends AsyncTask {
String companyNameS = companyName.getText().toString();
String modelNumberS = modelNumber.getText().toString();
String specificationS = specification.getText().toString();
#Override
protected Object doInBackground(Object[] objects) {
JSONObject jsonObjSend = new JSONObject();
JSONObject encrptObjSend = new JSONObject();
try {
jsonObjSend.put("Company", companyNameS);
jsonObjSend.put("Model Number", modelNumberS);
jsonObjSend.put("Specification", specificationS);
String finalData = jsonObjSend.toString();
Log.i("data", finalData);
String key = "HelloWorld321#!";
String encrypt;
try {
CryptLib cryptLib = new CryptLib();
String iv = "1234123412341234";
encrypt = cryptLib.encryptSimple(finalData, key, iv);
encrptObjSend.put("encrptedtext", encrypt);
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Encrypted data", encrptObjSend.toString());
JSONObject header = new JSONObject();
header.put("deviceType", "Android"); // Device type
header.put("deviceVersion", "2.0"); // Device OS version
header.put("language", "es-es"); // Language of the Android client
encrptObjSend.put("header", header);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObjRecv = HttpClient.SendHttpPost("https://192.168.43.59:443/api/aes", encrptObjSend);
return "success";
}
}
}
Update:
public class HttpClient {
private static final String TAG = "HttpClient";
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
private static 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.
*
* (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*/
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();
}
}
You should use an always-ok delegate to avoid server certificate validation. Of course you must use https connection. Check this link, for example: http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/
I have a web server, where i log in in my android Application, after that loging i recive as an XML the user who logged with a field named token.
This token is used to keep open the session during next calls to webService, and it works sendidnt the token as a cookie named "acrsession" but it seems not working because everytime i tried to check if im logged in (using a get call named currentUser) it returns me forbidden, so i think it isnt working good.
Here is my AsyncTask class who do the calls to server.
public String getFileName() {
return FileName;
}
public void setFileName(String fileName) {
FileName = fileName;
}
private String Response;
private URI uriInfo;
private String FileName;
public WebServiceTask(int taskType, Context mContext, String processMessage,String token) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
this.token=token;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
//hideKeyboard();
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
this.Response=response;
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
int responseCode=0;
// Create a local instance of cookie store
//CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
//HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
//localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//CookieManager cookieManager= CookieManager.getInstance();
this.getLocalContext();
this.cookieStore.addCookie(new BasicClientCookie("acrsession", this.token));
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
int executeCount = 0;
do
{
pDlg.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = httpclient.execute(httppost,localContext);
responseCode = response.getStatusLine().getStatusCode();
// If you want to see the response code, you can Log it
// out here by calling:
// Log.d("256 Design", "statusCode: " + responseCode)
} while (executeCount < 5 && responseCode == 408);
uriInfo = httppost.getURI();
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpget.getRequestLine();
uriInfo = httpget.getURI();
break;
case PUT_TASK:
HttpPut httpput = new HttpPut(url);
File file = new File(this.FileName);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httpput.setEntity(reqEntity);
response = httpclient.execute(httpput,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpput.getRequestLine();
uriInfo = httpput.getURI();
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
this.Response=total.toString();
return total.toString();
}
public String getResponse(){
return this.Response;
}
public HttpContext getLocalContext()
{
if (localContext == null)
{
localContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
localContext.setAttribute(ClientContext.COOKIE_ORIGIN, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_SPEC, cookieStore);
localContext.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);// to make sure that cookies provided by the server can be reused
}
return localContext;
}
Plesae tell me what im doing bad.
Thanks in advance.
Well, finally i found the solution, everything was ok but i fortgot to set cookie Domain and path, so onced i putted it it worked.
Now cookie creation looks like this:
this.localContext=this.getLocalContext();
BasicClientCookie cookie = new BasicClientCookie("acrsession", this.token);
cookie.setDomain(this.Domain);
cookie.setPath(this.path);
this.cookieStore.addCookie(cookie);
localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
Hope it will help someone else.
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.
I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want