I am using the apache httpClient post method to call a rest client API, but API is giving incorrect response so I want to debug the method and want to print the request in json format.
below is the code I am using-
private String baseUrl = "myIPAddress";
private HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseUrl + "app/registration");
try {
String line = "";
for (int rIndex = 0; rIndex < goodAuthenticationPairs.length; rIndex++) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("email","myEmail#test.com"));
nameValuePairs.add(new BasicNameValuePair("password","myPassword"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//post.setHeader("Content-type", "application/json");
System.out.println(post);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = rd.readLine();
System.out.println(line);
JSONObject json = (JSONObject) new JSONParser().parse(line);
String actualResult = json.get("return_code").toString();
assertTrue("0".equals(actualResult));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
I got the answer.
The code above is sending request in Content-Type: application/x-www-form-urlencoded but the server API expects Content-Type: application/json
Related
I need to do a POST request to SERVER by such example:
REQUEST FORMAT:
POST /oauth/authorize HTTP/1.1
Host: m.sp-money.yandex.ru (для мобильных устройств) или sp-money.yandex.ru (для остальных устройств)
Content-Type: application/x-www-form-urlencoded
Content-Length: <content-length>
client_id=<client_id>&response_type=code
&redirect_uri=<redirect_uri>&scope=<scope>
REQUEST PARAMETERS EXAMPLE:
client_id=092763469236489593523464667
response_type=code
redirect_uri=https://client.example.com/cb
scope=account-info operation-history
Now, I have been done a transfer for headers:
protected Void doInBackground(Void... arg)
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("HOST", "sp-money.yandex.ru"));
params.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
params.add(new BasicNameValuePair("Content-Length", "154"));
JSONObject testJSON = makeHttpRequest("https://money.yandex.ru/oauth/authorize", "POST", params);
int test = 1;
return null;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
{
try
{
if(method == "POST")
{
String responseText = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
String testStr = httpPost.toString();
HttpResponse httpResponse = httpClient.execute(httpPost);
responseText = EntityUtils.toString(httpResponse.getEntity());
int test = 1;
test = 0;
}
}
//.............................................
}
How can I do a transfer for parameters(client_id, response_type, redirect_uri, scope)?
And how can I get response from server?
RESPONSE EXAMPLE:
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=i1WsRn1uB1ehfbb37
In your doInBackground you can try something like this.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(HTTP_REQUEST_URL);
//create and assign post request server data
String latitude = loc.getLatitude() + "";
String longitude = loc.getLongitude() + "";
String time = DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) + "";
String whr = WhereAmI(loc.getLatitude(), loc.getLongitude());
//data back from server
String responseBackFromServer = "";
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("latitude", latitude));
pairs.add(new BasicNameValuePair("longitude", longitude));
pairs.add(new BasicNameValuePair("whereAmI", whr));
pairs.add(new BasicNameValuePair("time", time));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = client.execute(post);
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "Response Back: " + responseBackFromServer;
and In onPostExecute you can do whatever with the reponse.
My web service code is following i am using WCF Restful webservices,
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Login?parameter={parameter}")]
string Login(string parameter);
public string Login(string parameter)
{
/*
* input := {"username":"kevin","password":"123demo"}
* output:= 1=sucess,0=fail
*
*/
//Getting Parameters from Json
JObject jo = JObject.Parse(parameter);
string username = (string)jo["username"];
string password = (string)jo["password"];
return ""+username;
}
my client side(Android) code is following
JSONObject json = new JSONObject();
try {
json.put("username","demo");
json.put("password","password123");
HttpPost postMethod = new HttpPost(SERVICE_URI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
HttpClient hc = new DefaultHttpClient();
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception", ""+e);
}
I am getting following output after calling Web service:
The server encountered an error processing the request. See server
logs for more details.
Basically my problem is I am unable to pass value by using NameValuePair.
Following code worked for me:
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
}
return string;
}
I'm making an android app and run it on the simulator. All post parameters on the server are empty when I send a http post request. This is code in the android app:
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(page);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStreamReader inreader = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(inreader);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
And this is the code on the server:
<?php
print_r($_POST);
?>
It returns an empty php array when I run it on the simulator.
Put www in the request url and it was solved. There was a htaccess file that corrected all url`s without www.
Volley Library(sim-official from google) is better, http, https etc.
https://developers.google.com/live/shows/474338138
There's a very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
There's the same question like you here: Optimizing HTTP requests in android
I've tried several things but my android app is not sending post parameters. I run the app on a virtual device. This is the code:
#Override
public void run() {
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(isr);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
It should send a post request to a PHP page. This page displays the output of the POST array:
<?php
print_r($_POST);
?>
When I run the app, it displays an empty array.
thats because you're sending JSON
standard php $_POST is build from key-value pairs
so you should post key1=value1&key2=value2
or you should read from
$HTTP_RAW_POST_DATA
or
<?php $postdata = file_get_contents("php://input"); ?>
and use
json_decode( $postdata );
PHP will not automatically decode json for you
you can also use another approach and POST your json like data=YourJsonCode
and then decode it using json_decode( $_POST['data'] );
Try sending url encoded name/value pairs. You can also use EntityUtils to convert the response to a String for you.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
Problem solved. There was a htaccess file that redirected all non www pages.
For example if we need to send content which is in this format , how do we do it
{"name1":[{"name11":"value11"},{"name11":"value12"},{"name11":"value13"}],"name2":value2}
I know how to set the basic kind
{"name1":"value1","name2":value2}
NameValuePair[] nameValuePairs = new NameValuePair[2];
nameValuePairs[0]= new BasicNameValuePair("name1", "value1");
nameValuePairs[1] = new BasicNameValuePair("name2", value2);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
How can we achieve nesting
Please see this question as it has a couple of answers that should help you. Here is a brief snippet from the answers code:
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
The other answer says you can do something like this:
protected void sendJson(final String email, final String pwd) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( "JSON: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
}