HTTP Post Only works with default HttpClient, not with OkHttpClient - android

I'm working on a project which requires me to send a post request to
http://sagecell.sagemath.org/kernel (just a post, no data)along with two extra headers,
Accept-Encoding:identity and accepted_tos:true.
This works fine if using the default httpClient like so:
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
String url = UrlUtils.getKernelURL();
httpPost.setURI(URI.create(url));
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(HEADER_ACCEPT_ENCODING,VALUE_IDENTITY));
postParameters.add(new BasicNameValuePair(HEADER_TOS,"true"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
webSocketResponse = gson.fromJson(new InputStreamReader(inputStream), WebSocketResponse.class);
inputStream.close();
However if I want to use the same thing using the OkHttpClient, it gives me a 403 error:
httpClient = new OkHttpClient();
public static final MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonMediaType, "");
Request request = new Request.Builder()
.addHeader(HEADER_ACCEPT_ENCODING, VALUE_IDENTITY)
.addHeader(HEADER_TOS, "true")
.url(url)
.post(body) //I've tried null here as well
.build();
Response response = httpClient.newCall(request).execute();
Log.i(TAG,"STATUS CODE"+response.code()); //This is 403
This is the same story with libraries like Ion and even HttpUrlConnection, only the Apache Client seems to work.
Any answers as to why this isn't working would be appreciated.

error 403 means its forbidden by the server.
And in the first case(while using default httpclient ) you are not adding header, you are just adding a name-value pair to the entity.
to add a header you should use
httpPost.addHeader("key","value");

Your request body is empty. You should provide a form-encoded request body, or a JSON request body, and the corresponding content type.
If you want, MimeCraft will build you a form-encoded request body, and Gson will do JSON.

Related

Android :HttpGet with Params unsuccessful

I am using Apache HttpClient, DefaultHttpClient, HttpResponse to make HttpGet Request with JsonObject as request parameter. I receive response in JsonObject format.The Content-Type is application/json
The problem is once a login request fails by providing incorrect login details the next time you correct the details you always fail to get success response.
This scenario doesn't happen if the very first login is successful.
I suspect the params are not going through correctly although I have checked the same. Is there a possibility that the previous request is cached and the new params are not going through.
JSONObject inputBodyObject = new JSONObject();
inputBodyObject.put("email", emailId);
inputBodyObject.put("password", password);
String strURL = this.getString(R.string.base_url) + this.getString(R.string.action_login) + Uri.encode(inputBodyObject.toString());
HttpGet httpGet = new HttpGet(strURL);
httpGet.setHeader("Content-type", "application/json"));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();

Java Equivalent of curl query

I am trying to fetch current user info after making him log into his box, using the box sdk for android. In the box api documentation, they have mentioned everything using curls. I am not familiar with curl. So, can anyone please give me a java equivalent for this curl operation :
curl https://api.box.com/2.0/users/me-H "Authorization: Bearer ACCESS_TOKEN".
I have the users access token.So, please give me a java equivalent for the above curl operation.
You can use java HttpClient
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Authorization", "Bearer ACCESS_TOKEN"); // add headers if needded
//set params
BasicNameValuePair[] params = new BasicNameValuePair[] {new BasicNameValuePair("param1","param value"),
new BasicNameValuePair("param2","param value")};
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity( Arrays.asList(params), "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
//execute request
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity); //here response in string you can parse it
The HttpClient object that the other answer proposes is now deprecated. I solved a CURL problem like yours (with the extra difficulty of uploading a .wav file). Check out my code in this this answer/question. How to upload a WAV file using URLConnection

how to send object over Get Request in android

I want to send the below JSON request to a web service and read the response.
{"Email":"aaa#tbbb.com","Password":"123456"}
I know to how to read JSON. The problem is that the above JSON object must be sent in a variable name json.I want to send Json object as a parameter with get request.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet httpget = new HttpGet(FinalURL.toString());
//HttpPost request = new HttpPost(serverUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
You can set request using:
httpget.setEntity(new JSONObject(requestString));
One of the options i'm using right now is RequestParams:
It can be implemented as:
RequestParams rp = new RequestParams();
rp.put("Email", "aaa#tbbb.com");
rp.put("Password", "123456");
Utils.client.get(url, rp, new AsyncHttpResponseHandler() {
//or your http code
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
http://loopj.com/android-async-http/

posting the data using httpput in android

I have a problem in posting the data to server by using httpput methods in android.I have to send feedback to server and getting json response. but i am getting 404 bad request. but i dont know where is the problem.
I am strucked here and didn't find any solution. Any suggestions?
My code is as follows:
HttpClient client = new DefaultHttpClient();
HttpPut put = new HttpPut(getString(R.string.feedBack));
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("userId", "8"));
pairs.add(new BasicNameValuePair("feedback",feedbackMessage
.getText().toString()));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
Log.d(tag, "Result" + response.getStatusLine());
You are not initializing a URL object and passing in simple String.
You should do this instead:
URL url = new URL(getString(R.string.feedBack));
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
And it should work.

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

Categories

Resources