How to do POST request and get a response from server? - java

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.

Related

got empty string from json in android

So when i use postman(google app) to send a post method to my php file on my web server, i got a full respond back with all the correct information. but when i am trying to do the same thing on android, i am getting [] in response everytime.
#Override
protected Profile doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://www.secretvoice1.com/getData.php");
Profile returnUser = null;
try {
HttpResponse httpResponse = client.execute(post);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
HttpEntity entity = httpResponse.getEntity();
Log.d("11111:", httpResponse.toString());
String result = EntityUtils.toString(entity);
System.out.println(result);
Log.d("222222", result);
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() == 0) {
returnUser = null;
Log.d("this:", "here");
} else {
//String name = jsonObject.getJSONArray("name");
//String password = jsonObject.getString("password");
//String email = jsonObject.getString("email");
returnUser = new Profile(user.name, user.password, user.email);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}

How to print the httpPost request in json format?

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

Save zip file android

NODE.js : (zip the file)
app.post('/api/db', function(req, res){
if(req.body.type == 'Control'){
var zip = new AdmZip();
console.log(req.body.type);
zip.addLocalFolder(__dirname +'/XXX/Temp/1');
var willSendthis = zip.toBuffer();
zip.writeZip(__dirname +'/files.zip');
res.sendFile(zip);
}
});
JAVA : (send a request to want to zip file)
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
public ArrayList<String> aList= new ArrayList<String>();
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "Control"));
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String result) {
}
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "PUT"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
url = url.trim();
Log.d("url = ", URLEncoder.encode(url, "UTF-8"));
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-9"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I sent .zip file from server to android devices. I want to save into the android devices memory.
How can i save .zip file which is sended by node.js server?

Post again after login with cookie received

I am working on a login service that logs a user in then after a successful login it posts again to a new script with a cookie that was given on the login to get more info. here is my login post:
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testsite.com/login");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "john"));
nameValuePairs.add(new BasicNameValuePair("password", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Now from what ive read if I use the same hpptClient without starting a new one, when i do another post it will use the cookie that i recieved? where could I add a second post in my example or how would it look. Just getting started with android/Java so this is a little confusing for me.
Thanks.
You can use an HttpContext + CookieStore to keep track of cookie state between requests. I think something like this would work for you (untested):
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httppost = new HttpPost("http://testsite.com/login");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "john"));
nameValuePairs.add(new BasicNameValuePair("password", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost, localContext);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
And for your 2nd request, reuse the localContext variable:
// replace XXX below with correct URL
httppost = new HttpPost("http://testsite.com/XXXXXX");
try {
// set entities here ...
HttpResponse response = httpclient.execute(httppost, localContext);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

Android :-Consume a web service through Post method as a json Request and Response

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;
}

Categories

Resources