I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.
Related
I am trying to validate a login using the below code. My challenge is to how get a response of 200 status code and if yes display the welcome screen. This is my code attempt but it has no status to confirm is the post is successful thereafter take the next action.
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Please how can I modify the above form post code to return a status code and thereafter take the necessary step fron login screen
As the other said before me, try getting the status code from the HttpResponse:
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
HttpResponse response = makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/",json);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
showSplashScreen();
}else{
//ErrorHandling
}
}
I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"
I am uploading a file to server from my android application using the below code, and its working fine. now I want to pass a jsonobject also to servlet, I tried some way like
mpEntity.addPart("param",new StringBody(details.toString(),"text/plain",
Charset.forName("UTF-8")));
here the details is a JSON object, but its not working, so please help me to solve this.
this is my code(in android) for file uploading.
private class AsyncCaller extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
JSONObject obj=new JSONObject();
try {
obj.put("m1", "adad");
obj.put("m2", "adadad");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpPost httppost = new HttpPost(
"http://172.20.56.229:8084/AndroidTesting/UploadServlet");
File file = new File("/sdcard/CEA.txt");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFe = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFe);
httppost.setEntity(mpEntity);
System.out
.println("executing request " + httppost.getRequestLine());
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
httpclient.getConnectionManager().shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.