I face a problem to get Json data into my application. On get action. I have solve the problem for POST. We have a ssl certificate but seems for get and post the way is little different. I can't figure out. So if people can give me an help here. I will appreciate.
package com.example.administrator.superclass.Utils;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Looper;
import android.util.Log;
import com.example.administrator.superclass.MyApp;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Okhttp_Util {
public static String Ok_Get(Context context,String url, HashMap<String, String> hashMap) {
String data = "";
// OkHttpClient okHttpClient = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(10,TimeUnit.SECONDS)
// .build();
OkHttpClient okHttpClient= MyApp.handleSSLHandshake();
FormBody.Builder builder = new FormBody.Builder();
for (String key : hashMap.keySet()) {
builder.add(key, hashMap.get(key));
}
builder.build();
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).build();
try {
Response response = okHttpClient.newCall(request).execute();
data = response.body().string();
} catch (IOException e) {
if(e instanceof SocketTimeoutException){//判断超时异常
Looper.prepare();
if (ProgressDialog_Util.isshow){
ProgressDialog_Util.Dialog_dismiss();
}
Toast_util.Toast_show(context,"连接超时!请更换网络后重试!");
Log.e("geterr1: ",e.toString() );
Looper.loop();
}
if(e instanceof ConnectException){//判断连接异常,我这里是报Failed to connect to 10.7.5.144
Looper.prepare();
if (ProgressDialog_Util.isshow){
ProgressDialog_Util.Dialog_dismiss();
}
Toast_util.Toast_show(context,e.toString());
Log.e( "geterr2: ",e.toString() );
Looper.loop();
}
}
return data;
}
public static String Ok_Post(Context context,String url, HashMap<String, String> hashMap) {
String data = "";
// OkHttpClient okHttpClient = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(10,TimeUnit.SECONDS)
// .build();
OkHttpClient okHttpClient= MyApp.handleSSLHandshake();
FormBody.Builder builder = new FormBody.Builder();
for (String key : hashMap.keySet()) {
builder.add(key, hashMap.get(key));
}
builder.build();
RequestBody requestBody = builder.build();
Request request = new Request.Builder().post(requestBody).url(url).build();
try {
Response response = okHttpClient.newCall(request).execute();
data = response.body().string();
} catch (IOException e) {
if(e instanceof SocketTimeoutException){//判断超时异常
Looper.prepare();
if (ProgressDialog_Util.isshow){
ProgressDialog_Util.Dialog_dismiss();
}
Toast_util.Toast_show(context,"连接超时!");
Log.e("posterr1: ",e.toString() );
Looper.loop();
}
if(e instanceof ConnectException){//判断连接异常,我这里是报Failed to connect to 10.7.5.144
Looper.prepare();
if (ProgressDialog_Util.isshow){
ProgressDialog_Util.Dialog_dismiss();
}
Toast_util.Toast_show(context,e.toString());
Log.e( "posterr2: ",e.toString() );
Looper.loop();
}
}
return data;
}
}
From the compilation i get an error :
enter image description here
The error indicates that you are calling your get request without passing a HashMap.
My suggestion would be to either pass an empty HashMap if you have some URLs that require a body. Else remove it entirely:
public static String Ok_Get(Context context,String url) {
String data = "";
OkHttpClient okHttpClient= MyApp.handleSSLHandshake();
FormBody.Builder builder = new FormBody.Builder();
builder.build();
Request request = new Request.Builder().url(url).build();
If you still need it, when you call it make sure you include the HashMap:
Ok_Get(context, "your/url/string/here", Collections.<String, String>emptyMap())
Related
I'm using msl4j to interact with microsoft products, e.g. emails, calendars. When I call the user informations (without parameters) this will works fine. But, when I try to read messages from the inbox, the call ended with error 404 ("code":"ResourceNotFound","message":"Resource could not be discovered."). I don't know why. The API Permissions seems correct.
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.DeviceCode;
import com.microsoft.aad.msal4j.DeviceCodeFlowParameters;
import com.microsoft.aad.msal4j.IAccount;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.MsalException;
import com.microsoft.aad.msal4j.OnBehalfOfParameters;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.microsoft.aad.msal4j.SilentParameters;
import com.microsoft.aad.msal4j.UserAssertion;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class AppMSAL4J {
private static String userId;
private static String authority;
private static String clientId;
private static String clientSecret;
private static String tenantId;
private static Set<String> scopes;
public static void main(String args[]) throws Exception {
setUpSampleData();
try {
IAuthenticationResult result = acquireToken();
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String bodyString = "";
RequestBody body = RequestBody.create(bodyString, mediaType);
String baseUrl = "https://graph.microsoft.com/v1.0/users/" + userId;
String parameters = "";
// parameters = "/mailfolders('Inbox')/messages";
// parameters = "/messages";
Request request = new Request.Builder()
.url(baseUrl + parameters)
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + result.accessToken())
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static IAuthenticationResult acquireToken() throws Exception {
IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication cca = ConfidentialClientApplication
.builder(clientId, credential)
.authority(authority)
.build();
ClientCredentialParameters parameters = ClientCredentialParameters
.builder(scopes)
.build();
return cca.acquireToken(parameters).join();
}
private static void setUpSampleData() {
userId = "b0f***";
tenantId = "fc2***";
authority = "https://login.microsoftonline.com/" + tenantId;
clientId = "b1a***";
clientSecret = "KJ***";
scopes = Collections.singleton("https://graph.microsoft.com/.default");
}
}
I try to make a second request in the HttpAsyncClient callback. But the second request is on wait state.
Example code:
package com.example.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import java.util.concurrent.Future;
public class AsyncClientHttpExample {
public static void main(String[] args) {
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
final HttpGet request1 = new HttpGet("http://httpbin.org/ip");
httpClient.execute(request1, new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse result) {
try {
System.out.println(EntityUtils.toString(result.getEntity()));
final HttpGet anotherRequest = new HttpGet("http://httpbin.org/headers");
Future<HttpResponse> future1 = httpClient.execute(anotherRequest, null);
HttpResponse anotherResponse = future1.get(); //the code get hand up here.
System.out.println("response 1 " + anotherResponse);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Override
public void failed(Exception ex) {
System.out.println(ex);
}
#Override
public void cancelled() {
}
});
}
}
I don't quite understand why the second request got hand up in the anotherResponse. I thought the second request is waiting for some lock that has already captured by request 1. But I haven't figure that out.
I am trying to integrate ClickSend for sending sms.
Able to send the sms using below code:
SmsApi apiInstance = new SmsApi(defaultClient);
SmsMessage smsMessage1 = new SmsMessage();
smsMessage1.body("Test SMS 1");
smsMessage1.to("+61411111111");
smsMessage1.source("Java");
List<SmsMessage> smsMessageList = Arrays.asList(smsMessage1);
SmsMessageCollection smsMessages = new SmsMessageCollection();
smsMessages.messages(smsMessageList);
try {
String result = apiInstance.smsSendPost(smsMessages);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SmsApi#smsSendPost");
e.printStackTrace();
}
Response format is String. But no class provided for it.
Its hard to retrieve the data for multiple SmsMessage.
How to read response of ClickSend smsSendPost in Java SDK ?
Is there any class available which holds response like SmsMessage, SmsMessageCollection in Java SDK of ClickSend.
Hopefully this will help:
package com.example.demo;
import ClickSend.*;
import ClickSend.auth.*;
import ClickSend.Model.*;
import ClickSend.Api.AccountApi;
import ClickSend.Api.SmsApi;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.util.*;
public class SMS {
public static void main(String[] args) {
sendSMS();
}
public static void sendSMS() {
ApiClient defaultClient = new ApiClient();
defaultClient.setUsername("your_login#email.com");
defaultClient.setPassword("SecretPa$$word!");
SmsApi apiInstance = new SmsApi(defaultClient);
SmsMessage smsMessage=new SmsMessage();
smsMessage.body("This is the body of the message");
smsMessage.to("+6111111111");
smsMessage.source("java");
List<SmsMessage> smsMessageList=Arrays.asList(smsMessage);
SmsMessageCollection smsMessages = new SmsMessageCollection();
smsMessages.messages(smsMessageList);
try {
String result = apiInstance.smsSendPost(smsMessages);
System.out.println(result);
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
JsonArray messageArray = jsonObject.getAsJsonObject("data").getAsJsonArray("messages");
// Here is the array and how to grab some stuff out of it.
// Could also use messageArray.forEach here
for( int i = 0; i <= messageArray.size(); i++ ) {
JsonObject message = messageArray.get(i).getAsJsonObject();
double price = message.get("message_price" ).getAsDouble();
String body = message.get("body").getAsString();
System.out.printf( "It cost %f to send '%s'\n", price, body);
}
} catch (ApiException e) {
System.err.println("Oops");
e.printStackTrace();
}
}
}
Hi i have created a handler in java for getting the events from dynamo DB
Here is my code
package com.Lambda.dynamodb;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
public class DDBEventProcessor implements
RequestHandler<DynamodbEvent, String> {
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()){
System.out.println(record.getEventID());
System.out.println(record.getEventName());
System.out.println(record.getDynamodb().toString());
}
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
}
}
Lambda function able to write the events in cloudwatch but the challenge is i have to index all the streamed records to the AWS elasticsearch service endpoint and index it.
while search through blogs i got few code samples in python and node.js but my requirement is i have to build this lambda function in java
Could anyone please suggest how to achieve this in java lambda function?
Hi i have included the code below may helpful to some one. Dynamo DB streams to index the document in elasticsearch both inside AWS and outside AWS
package com.Firstlambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HelloWorld implements RequestHandler<DynamodbEvent, String> {
private static String serviceName = "es";
private static String region = "us-east-1";
private static String aesEndpoint = ""
private static String index = "";
private static String type = "_doc";
static final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()) {
System.out.println("EventName : " + record.getEventName());
System.out.println("EventName : " + record.getDynamodb());
//AWS outside
RestHighLevelClient esClient = esClient();
//AWS outside
//AWS Inside
//RestHighLevelClient esClient = esClient(serviceName, region);
//AWS Inside
if (record.getEventName().toLowerCase().equals("insert")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
IndexRequest indexRequest = new IndexRequest(index, type, JsonUniqueId);
indexRequest.source(JsonString, XContentType.JSON);
try {
IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else if (record.getEventName().toLowerCase().equals("modify")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
UpdateRequest request = new UpdateRequest(index, type, JsonUniqueId);
String jsonString = JsonString;
request.doc(jsonString, XContentType.JSON);
try {
UpdateResponse updateResponse = esClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("remove");
System.out.println("KEYID : " + record.getDynamodb().getKeys().get("ID").getN());
String deletedId = record.getDynamodb().getKeys().get("ID").getN();
DeleteRequest request = new DeleteRequest(index, type, deletedId);
try {
DeleteResponse deleteResponse = esClient.delete(
request, RequestOptions.DEFAULT);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return "Successfullyprocessed";
}
public String getJsonstring(Map<String, AttributeValue> newIma) {
String json = null;
Map<String, AttributeValue> newImage = newIma;
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = ItemUtils.toItemList(listOfMaps);
for (Item item : itemList) {
json = item.toJSON();
}
return json;
}
public String GetIdfromJsonString(String Json) {
JSONObject jsonObj = new JSONObject(Json);
return String.valueOf(jsonObj.getInt("ID"));
}
// Adds the interceptor to the ES REST client
// public static RestHighLevelClient esClient(String serviceName, String region) {
// AWS4Signer signer = new AWS4Signer();
// signer.setServiceName(serviceName);
// signer.setRegionName(region);
// HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
// return new RestHighLevelClient(RestClient.builder(HttpHost.create(aesEndpoint)).setHttpClientConfigCallback(hacb -> hacb.addInterceptorLast(interceptor)));
// }
public static RestHighLevelClient esClient() {
String host = "d9bc7cbca5ec49ea96a6ea683f70caca.eastus2.azure.elastic-cloud.com";
int port = 9200;
String userName = "elastic";
String password = "L4Nfnle3wxLmV95lffwsf$Ub46hp";
String protocol = "https";
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
This is just a sample code has to be modified based on our requirements
I am creating an app for Phillips Hue Lights and I want to be able to click a button, which will do the post request from my app to a specific URL of the Hue Bridge to get a username returned.
My Code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
public class Device extends AppCompatActivity {
HashMap<String, String> params = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
{
params.put("devicetype", "final_year_project#michelle");
PostHandler handler = new PostHandler(params);
try {
JSONObject response = handler.execute("http://192.168.1.85/api/").get();
Log.d("TEST_RESPONSE", response.toString());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
I have also created my PostHandler class:
import android.os.AsyncTask;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostHandler extends AsyncTask<String, Void, JSONObject> {
OkHttpClient client = new OkHttpClient();
HashMap<String, String> params = new HashMap<>();
public PostHandler(HashMap params) {
this.params = params;
}
public PostHandler() {
}
#Override
protected JSONObject doInBackground(String... url) {
client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
FormBody.Builder body = new FormBody.Builder();
for ( Map.Entry<String, String> entry : params.entrySet() ) {
body.add( entry.getKey(), entry.getValue() );
}
RequestBody formBody = body.build();
Request request = new Request.Builder()
.url(url[0])
.post(formBody)
.build();
try{
Response response = client.newCall(request).execute();
String result = response.body().string();
JSONObject json = new JSONObject(result);
return json;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
I am getting an error "cannot resolve symbol params" and the post request does not work.
Does anyone know where I am going wrong? I am new to working with API's.
Add the following line after setContentView(R.layout.activity_device);:
ContentValues params = new ContentValues();
You have not declared the variable params anywhere in your code.