Where do I put the REST Client Authentication Data in the Query? - java

I need to work with REST api in android application which is created by my client. Below text is just copied from the pdf the client provides us.
--
In this example, a new user is created.
The parts of a possible request to the server is shown below:
Message part Contents
Header POST {url-prefix}/rest/user
Content-Type: application/xml
Content-Length: 205
Body <request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
--
After searching and studying, I come to know that, the possible request code (in Java) might be:
URL url=new URL("http://api.example.com/rest/user/?name=myUserName&password=myUserPassword&groupId=12345");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("Post");
OutputStreamWriter out=new OutputStreamWriter(conn.getOutputStream());
out.write("respose content:");
out.close();
From the pdf manual they provide, I got to know, for every request to the server, the client (thats me) has to transmit the authentication data.
My question is, where do I put the authentication data in the query string? Please help me on this.
Edit:After posting the below code as request:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.example.com/rest/user/?name=Foysal&password=123456&groupid=12345");
httpPost.addHeader("Accept", "text/xml");
httpPost.setHeader("Content-Type","application/xml;charset=UTF-8");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", "APIappDevAccount"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
httpClient.setParams(params);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf;
int ByteRead;
buf = new byte[1024];
String xmldata = null;
double totalSize = 0;
while ((ByteRead = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, ByteRead);
totalSize += ByteRead;
}
xmldata = os.toString();
os.close();
is.close();
But I got the response as:
404
Not Found
Not Found The requested
URL /rest/user/ was not found on this
server. Apache/2.2.6
(Fedora) DAV/2 mod_ssl/2.2.6
OpenSSL/0.9.8b Server at
api.example.com Port 80

Looks to me like they want you to POST an XML document and put the authentication in that. Not much of a REST API (most REST APIS don't require an XML document).
You need to use conn.getOutputStream() to send that doc to the server and use conn.getInputStream() to read the response.
So you would have to create the XML doc like the one they show:
<request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
And then send it in your POST:
conn.setRequestProperty ( "Content-Type", "text/xml" );
out.write(requestDoc); //where requestDoc is the String containing the XML.
out.flush();
out.close();

You may execute a POST request like shown here: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient and put the authentication data as name value pairs:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "myUserName"));
nameValuePairs.add(new BasicNameValuePair("password", "myUserPassword"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// ... handle exception here
}

Related

HttpPost return a empty body

I have the code below, and my problem is that the response.status is 200 (is ok) and my response body is empty and it should return a json response. Is the problem the length maybe?:`
HttpPost post = new HttpPost("http://localhost:8080/rest/login");
httpClient = HttpClients.createDefault();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
NameValuePair pair = new BasicNameValuePair("token",token);
formParams.add(pair);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
this.code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));`
I had similar problem. In my case it was also very strange, that when url contained IP instead of hostname, it worked (I get the nonempty response).
However, setting netscape cookie specs helped in my case.
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.NETSCAPE)
.build());

HttpPost view post params

I'd like to be able to view the complete HttpClient / HttpPost URI with params. I'm not sure how to output it to my console.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("ContentType","application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
System.out.println(httppost.getURI());
Printing getURI only outputs the baseURI and not the params.
Could someone help me with what I'm missing?
The entity has a method to serialize itself to an output stream writeTo(), so you can create one and dump the entity there. This is not the whole request, only the UrlEncodedFormEntity exposing the encoded parameters:
ByteArrayOutputStream outs = new ByteArrayOutputStream();
httppost.getEntity().writeTo(outs);
System.out.println(outs.toString("UTF-8"));
outs.close();
result is one line like this:
foul=play&foo=bar&baz=bam

settHeader ("content type", "") - confusion

I have a function with which I want to POST two variables to the php side, after these two variables match and the server processes the result, I want to return result in JSON. As of now my set header property looks like the following:
httppost.setHeader("Content-type", "application/json");
But while reading on at Wikipedia I found that the content type should be application/x-www-form-urlencoded and to accept JSON it should be Accept: application/json I want more clarity on this, how do I modify my code to achieve my desired result? As of now I am using local host and my POST variables seem to be not delivered on the php side. Following is my complete function:
public void parse(String last, String pwd){
String lastIndex = last;
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
System.out.println("URL is: "+CONNECT_URL);
HttpPost httppost = new HttpPost(CONNECT_URL);
httppost.setHeader("Content-type", "application/json");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", password));
nameValuePairs.add(new BasicNameValuePair("last_index", lastIndex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("Post variables(Key): "+password+"");
System.out.println("Post variables(last index): "+lastIndex);
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println("Result: "+result);
// readAndParseJSON(result);
}catch (Exception e){
System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
// return result;
}
You have a caps problem. Try "Content-Type" rather than "Content-type" (or use the const HTTP.CONTENT_TYPE).
It appears that your code is actually doing what that article describes, except that
// httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
You are adding the x-www-form-urlencoded content here
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

UrlEncodedFormEntity equivalent in javascript

In java while doing an HTTP post request using nameValuePairs we write the following code!
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sometesturl.com");
JSONObject json = new JSONObject();
json.put("id",1);
json.put("name","john");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", "abc"));
nameValuePairs.add(new BasicNameValuePair("samplejson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
As seen over here we use the UrlEncodedFormEntity to encode our request body. Similarly, I need to do the same in Javascript. I have seen the EncodeURIComponent method but that doesn't seem to encode the request body. Instead it encodes the URL.
Can someone tell me how to encode the request body in javascript?

Android: HttpPost not work

Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);

Categories