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/
Related
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();
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.
Trying to send file content to server from Android application like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
final InputStreamEntity reqEntity = new InputStreamEntity(
gdFileSystemDelegate.openFileInput(openFileInput(FilePath), -1);
reqEntity.setContentType("application/octet-stream");
httppost.setEntity(reqEntity);
httpClient.execute(httppost);
But its throws an exception:
cannot retry request with a non-repeatable request entity
What does it mean ? how to fix that ?
Try to set protocol param http.protocol.expect-continue to true in DefaultHttpClient:
#Override
protected HttpParams createHttpParams() {
HttpParams params = super.createHttpParams();
HttpProtocolParams.setUseExpectContinue(params, true);
return params;
}
I'm trying to post combination of string to my backend server. How can I achieve that using BasicNameValuePair. Here are some code which I was trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost("API HERE");
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));
I want to send username and password like:
username=USER&password=PWD
How to achieve the successful post to the server.
Help will be appreciated.
The following is what I use for all of my POST variables:
HttpParams httpParams = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost;
httpPost = new HttpPost(Net_URL + Net_Get);
httpPost.setEntity(new UrlEncodedFormEntity(/*Name Value Pairs*/));
HttpResponse response = httpClient.execute(httpPost);
As a side suggestion, I would first do an some sort of encryption of a users password before sending it over the network, I have seen many who do not do this ^.^
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.