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.
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.
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 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())
I have made a java class to handle HTTP post requests and it sends back the result in string form. For some reason when I send the request I can print the response to the log but when return the string of the response to update the UI in the method my app crashes. Could any one explain whats happening here? I am trying to get better at java so pointing out any other bad practices would be appreciated .
log:
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/OKHTTP3: Request body created
D/OKHTTP3: Request body created 2
D/OKHTTP3: Got Response
D/OKHTTP3: {
"failed": "Asset already exists"
}
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.john.okhttp, PID: 3166
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.IllegalStateException: closed
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:374)
at okio.Buffer.writeAll(Buffer.java:993)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:106)
at okhttp3.ResponseBody.bytes(ResponseBody.java:128)
at okhttp3.ResponseBody.string(ResponseBody.java:154)
at com.example.john.okhttp.PostEx.doPostRequest(PostEx.java:40)
at com.example.john.okhttp.MainActivity$Requesting.doInBackground(MainActivity.java:59)
at com.example.john.okhttp.MainActivity$Requesting.doInBackground(MainActivity.java:51)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Application terminated.
the code from both java files will be posted below:
MainActivity.java:
package com.example.john.okhttp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class MainActivity extends AppCompatActivity {
private Button btnSendHttpRequest;
private EditText etJsonResponse;
private TextView View;
private TextView View2;
private OkHttpClient okHttpClient;
private Request request;
public final String URL = "http://www.mocky.io/v2/582ac99c280000d50953c316";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set button and text view values
btnSendHttpRequest = (Button) findViewById(R.id.btnSendRequest);
View = (TextView) findViewById(R.id.view1);
View2 = (TextView) findViewById(R.id.textView4);
etJsonResponse = (EditText) findViewById(R.id.etjson);
//response for button
btnSendHttpRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//http request
PostEx example = new PostEx();
new Requesting().execute();
}
});
}
public class Requesting extends AsyncTask<String, String, String> {
// post request stuff
#Override
protected String doInBackground(String... params) {
String id = "444454";
String userName = "john";
PostEx example = new PostEx();
String jsonstr = example.makeJsonForUser(id, userName);
if(example.doPostRequest(jsonstr)== null){
Log.d("OKHTTP3", "null pointer");
}
String response = example.doPostRequest(jsonstr);
Log.d("OKHTTP3", "sending response");
return response;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
//rewrite text view
try {
// create json ob from response
if(response == null){
Log.d("OKHTTP3", "null pointer");
}
JSONObject jsonObj = new JSONObject(response);
//get the values from the json key value pairs
String id = jsonObj.toString();
//update the text views
TextView textView = (TextView) findViewById(R.id.view1);
textView.setText(id);
} catch (Exception e) {
}
}
}
}
PostEx.java:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostEx {
public String doPostRequest(String jsonstr) {
String url = "http://45.55.92.243/newuser";
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON,jsonstr);
Log.d("OKHTTP3","Request body created");
Request newReq = new Request.Builder()
.url(url)
.post(body)
.build();
Log.d("OKHTTP3","Request body created 2");
try {
Response response = client.newCall(newReq).execute();
Log.d("OKHTTP3","Got Response");
Log.d("OKHTTP3",response.body().string());
String Fresponse = response.body().string();
response.close();
return Fresponse;
} catch (IOException e) {
Log.d("OKHTTP3","Got Exception");
e.printStackTrace();
return null;
}
}
public String makeJsonForUser(String id, String Username){
JSONObject data = new JSONObject();
try {
data.put("id", id);
data.put("name", Username);
return data.toString();
} catch (JSONException e) {
Log.d("OKHTTP3", "JSON Exeption");
e.printStackTrace();
return null;
}
}
}
at okhttp3.ResponseBody.string(ResponseBody.java:154):
public final String string() throws IOException {
return new String(bytes(), charset().name());
}
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:374):
#Override public long read(Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount);
if (closed) throw new IllegalStateException("closed");
if (bytesRemaining == 0) return -1;
long read = source.read(sink, Math.min(bytesRemaining, byteCount));
if (read == -1) {
endOfInput(false); // The server didn't supply the promised content length.
throw new ProtocolException("unexpected end of stream");
}
bytesRemaining -= read;
if (bytesRemaining == 0) {
endOfInput(true);
}
return read;
}
Your code works, mostly, up to this point
D/OKHTTP3: Request body created
D/OKHTTP3: Request body created 2
D/OKHTTP3: Got Response
I remember reading, you can only receive the body string once
// Log.d("OKHTTP3",response.body().string());
String Fresponse = response.body().string();
// log Fresponse here
And close the resources in a finally block after the catch
More importantly you are using Okhttp. You don't need Asynctasks! Use the enqueue method instead of execute on the client call object
client.newCall(newReq).enqueue(new Callback() {
// handle response here
});
And you're processing JSON, so Retrofit would help you implement what you're already trying to do
The problem is you can call string() once. But I don't know why