Volley JSONObjectRequest Request.Method.POST but received GET - java

I made a Custom JSONObjectRequest as below code.
Currently i made the Request.Method.POST and i had confirmed it while passing to the super class here
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);. It was received as int 1 (POST), but when received on my server (PHP), the log was receiving as "REQUEST_METHOD":"GET"
Have anyone met this kind of problem or can help to point out what i had missed in below code.
As you can see below, i had make sure below things:
params not empty
there is function getParams() there and the params are not empty
i even put getBody() and make sure it not returning null
Refer below code for what i had tried to do
try {
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (jsonObject != null && jsonObject.length() > 0) {
try {
if (jsonObject.getInt("status") == ResponseCode.LOGIN_FAILED) {
SharedManager sharedManager = new SharedManager();
sharedManager.logoutUser(context, true);
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
callback.onSuccessResponse(jsonObject);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onErrorResponse(error);
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
try {
return JSONHelperConverter.jsonToMapString(params);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8;";
}
#Override
public byte[] getBody() {
try {
String postBody = null;
try {
postBody = createPostBody(JSONHelperConverter.toMapString(params));
postBody = params.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return postBody == null ? null : postBody.getBytes("utf-8");
} catch (NegativeArraySizeException n) {
n.printStackTrace();
return null;
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
return null;
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
String responseString;
JSONObject jsonObject = null;
if (response != null) {
try {
responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
jsonObject = new JSONObject(responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
}
};
NetworkSingleton.getInstance(context).addToRequestQueue(stringRequest);
} catch (NegativeArraySizeException n) {
n.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

I solved my own problem
Sent POST request but server says GET request in Android volley, what I am doing wrong here?
Solution:
Due to i'm requesting to PHP server, i need to point out the filename.
Currently i point the request to a URL without Filename extension, and i just add index.php to my end of URL and it worked.

Related

java.net.ConnectException when Request to nonstandard HTTP/HTTPS port

I want to access REST server to activate my software. For this, I provide an URL, request body, and some credentials. When I use port 3000 (URL http://localhost:3000/activation), I got java.net.ConnectException. But it be normal when use port 80 or 443.
FYI, my simulator already run and I can access it by Postman.
How can I access port 3000 or other port using HttpClient?
This is my code in Java 1.8
private static ResponseEntityCustom sendRequestHttp(String method, String url, Map<String, List<String>> parameters, Headers requestHeaders, String body, int timeout) throws HttpRequestException {
Builder builder = HttpRequest.newBuilder();
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("uri.getPort(); = "+uri.getPort());
builder.uri(uri);
builder.timeout(Duration.ofMillis(timeout));
System.out.println("URL : "+url);
System.out.println("Method : "+method);
if(method.equalsIgnoreCase(HttpMethod.POST) ||
method.equalsIgnoreCase(HttpMethod.PUT) ||
method.equalsIgnoreCase(HttpMethod.PATCH)
)
{
if(body == null && parameters != null)
{
body = Utility.buildQuery(parameters);
}
if(body != null)
{
builder.method(method, BodyPublishers.ofByteArray(body.getBytes()));
}
}
else if(method.equalsIgnoreCase(HttpMethod.DELETE))
{
builder.DELETE();
}
else if(method.equalsIgnoreCase(HttpMethod.GET))
{
builder.GET();
}
for(Map.Entry<String, List<String>> entry : requestHeaders.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue())
{
builder.header(key, value);
}
}
HttpRequest request = builder.build();
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofMillis(timeout))
.build();
HttpResponse<String> response;
ResponseEntityCustom responseEntity = new ResponseEntityCustom();
try {
response = client.send(request, BodyHandlers.ofString());
System.out.println("response = "+response.toString());
responseEntity = new ResponseEntityCustom(response.body(), response.statusCode(), response.headers());
}
catch (InterruptedException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
catch(ConnectException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
catch(IOException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
return responseEntity;
}

Retrieving JSONObject from API in Android Studio

I am having an error in the method that retrieves the JSONObject and converts it to a string, the error says "!DOCTYPE of type java.lang.String cannot be converted to JSONObject"
public class FindSentimentTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String toReturn= "DID NOT WORK";
try
{
toReturn=getResponseFromHttpUrl(url[0]);
}catch (Exception e)
{
Log.d("ErrorInApp","exception on get Response from HTTP call" + e.getMessage());
return toReturn;
}
return toReturn;
}
protected void onPostExecute(String sentimentData) {
try {
JSONObject sentimentJSON = new JSONObject(sentimentData);
((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());
//String testOutput = sentimentJSON.get("docs").toString();
//((TextView)findViewById(R.id.output)).setText(testOutput.toString());
} catch (Exception e) {
Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
}
}
}
public static String getResponseFromHttpUrl(String url) throws IOException {
URL theURL = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) theURL.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
More specificaly the error is here where I retrieve the JSONObject and turn it into a string to display in a TextView
protected void onPostExecute(String sentimentData) {
try {
JSONObject sentimentJSON = new JSONObject(sentimentData);
((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());
} catch (Exception e) {
Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
}
}
The API I am using is https://developer.nytimes.com/article_search_v2.json

BasicNetwork.performRequest: Unexpected response code 400 for https://api.infermedica.com/v2/diagnosis - Android Java

I'm testing the inter media API and I am trying it using this code below. I used volley for this:
String url = "https://api.infermedica.com/v2/diagnosis";
JSONArray evidence = new JSONArray();
JSONObject evidence1 = new JSONObject();
try {
evidence1.put("id", "s_1193");
evidence1.put("choice_id", "present");
} catch (JSONException e) {
e.printStackTrace();
}
try {
evidence.put(0,evidence1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject postparams = new JSONObject();
try {
postparams.put("sex", "male");
postparams.put("age", 30);
postparams.put("evidence", evidence);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("DATA:", postparams.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(Object response) {
Log.e("DATA: ", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Log.e("DATA:" , obj.toString());
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("app-id", "MY-APP-ID");
headers.put("app-key", "MY-APP-KEY");
headers.put("authorization", "Basic Og==");
headers.put("Content-type", "application/json");
return headers;
}
};
Log.e("DATA: " , "calling volley");
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjReq);
After running it and checking the logs here is the result:
E/DATA:: {"sex":"male","age":30,"evidence":
[{"id":"s_1193","choice_id":"present"}]}
E/DATA:: calling volley
E/Volley: [236] BasicNetwork.performRequest: Unexpected response code 400
for https://api.infermedica.com/v2/diagnosis
E/DATA:: {"message":"bad request"}
I tried the logged json in Postman and it was accepted:
Here is the screenshot of my postman result
I've been looking for answers around here, I already added the content-type, and I made sure that my keys are correct. Am I using the volley correctly. Your help will be much appreciated.

Android volley. Cannot get JSON Response from a working Rest API

I tested my REST service in POSTMAN and it works. I should get something like this:
{
"msg": "the user was successfully created"
...
}
but in my android app in debug cannot find the response. Have I missed something or am I doing something wrong? Thanks!
private void registerUser(final String firstName, final String lastName,
final String email, final String password) {
pDialog.setMessage("Registering ...");
showDialog();
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonBody = new JSONObject();
jsonBody.put("first_name", firstName);
jsonBody.put("last_name", lastName);
jsonBody.put("email", email);
jsonBody.put("password", password);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
In debug, the block
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
displays this:
I have no JSON response.
You don't see any json data because you are not generating any json response from you side. The response you see on Postman is from the api service. You have a success response from your program (i.e. Status code 201) and that's the only thing you are sending back to the client.
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
You have to manipulate the response (in parseNetworkResponse module) and forward the relevant info you want to your client.

Conversion of HttpClient written in java to C# FOR calling Web apis

I am extremely new to C# And windows app programming.
I am trying to create an AsyncTask, like in java , where i can query a url and get its response back.
Here is the code i usually use in java, i want to implement the copy in C sharp.
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
private ResponseCallback myResponse = null;
private int type = 0;//POST
List<NameValuePair> nameValuePairs = null;
StringEntity entity = null;
private HttpResponse response = null;
public MyAsyncTask(String url,ResponseCallback myResponse)
{
this.myResponse = myResponse;
this.execute(url);
}
#Override
protected String doInBackground(String... param)
{
String url = param[0];
response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == 0)
{
HttpPost httppost = new HttpPost(url);
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
if (entity != null)
httppost.setEntity(entity);
response = httpclient.execute(httppost);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
} catch (IOException e)
{
}
String resp = null;
if (response != null)
{
try {
resp = Utilities.convertStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
else
return null;
}
#Override
protected void onPostExecute(String resp)
{
if (resp != null)
{
if (response.getStatusLine().getStatusCode() == Constants.RESULT_OK )
{
try {
myResponse.onSuccess(resp.trim());
} catch (IllegalStateException e) {
}
}
else
myResponse.onFailure(resp);
}
else
myResponse.onFailure(resp);
}
}
I have tried this in C #. Anyone wanna help me fix few things in this code and give me some info, what to do next
namespace The_Vow.Global
{
class MyAsyncTask
{
public ResponseCallback callback;
static void queryUrl(String url)
{
RunAsync(url).Wait();
}
static async Task RunAsync(String url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("MY_IP");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync(url);
//response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
String jsonStr = await response.Content.ReadAsStringAsync();
// callback variable is not being recognized????
callback.onSuccess(jsonStr);
//Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
}
}
}
namespace The_Vow.Global
{
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
}
Your callback field is an instance field, so you can't access it from a static method, unless you make the field static.
Another alternative I would like to recommend though, is not using a field at all. Pass the callback variable as a method argument.
Or you can stop using static methods at all, make them instance methods.

Categories