connecting to a php api from java - java

I am trying to connect to an api written in php from a java client.
For simplicity of the issue, I reduced the api to the following: (which simply returns the request given to the server)
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
$applications = array(
'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key for php client
'APP002' => '38e336ac6c9423d946ba02d19c6a2632' // for java app
);
require_once 'models/TodoItem.php';
echo"request";
foreach ($_REQUEST as $result) {
echo $result;
echo "<br>";
}
echo"end";
exit();
I am sending the request as follows: (string param is the string in the code snippet after this)
URL url;
HttpURLConnection connection = null;
try {
url = new URL(APP_URI);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(param.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (param);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
// read from input stream
The request string being passed is as follows: (a json object with 2 params, one of which is another json object)
{"app_id":"APP002","enc_request":"{\"username\":\"nikko\",\"action\":\"checkUser\",\"userpass\":\"test1234\",\"controller\":\"todo\"}"}
The reply is as follows, which consist only of the start and end tags I'm manually echoing and no content:
requestend
Why am I not getting any content on the server side?

I ended up using apache's httpclient api. By combining the answers from the following questions: Sending HTTP POST Request In Java
and What's the recommended way to get the HTTP response as a String when using Apache's HTTP Client? I go the following solution.
Note: The app_id and enc_request which i was sending as part of json are now as part of a namedpair, which adheres to the array being expected on the server side. Hence, the param string is now only:
{"username":"nikko","action":"checkUser","userpass":"test1234","controller":"todo"}
The code is as follows:
public static String excutePost(String[][] urlParameters) {
try {
String param = encode(urlParameters);
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(APP_URI);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("app_id", APP_NAME));
params.add(new BasicNameValuePair("enc_request", param));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String res = EntityUtils.toString(entity);
return res;
}
} catch (IOException e) {
return null;
}
return null;
}

Related

Send HTTPS request with JSON through Java [duplicate]

I would like to make a simple HTTP POST using JSON in Java.
Let's say the URL is www.site.com
and it takes in the value {"name":"myname","age":"20"} labeled as 'details' for example.
How would I go about creating the syntax for the POST?
I also can't seem to find a POST method in the JSON Javadocs.
Here is what you need to do:
Get the Apache HttpClient, this would enable you to make the required request
Create an HttpPost request with it and add the header application/x-www-form-urlencoded
Create a StringEntity that you will pass JSON to it
Execute the call
The code roughly looks like (you will still need to debug it and make it work):
// #Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
// #Deprecated httpClient.getConnectionManager().shutdown();
}
You can make use of Gson library to convert your java classes to JSON objects.
Create a pojo class for variables you want to send
as per above Example
{"name":"myname","age":"20"}
becomes
class pojo1
{
String name;
String age;
//generate setter and getters
}
once you set the variables in pojo1 class you can send that using the following code
String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
and these are the imports
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
and for GSON
import com.google.gson.Gson;
#momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
It's probably easiest to use HttpURLConnection.
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
You'll use JSONObject or whatever to construct your JSON, but not to handle the network; you need to serialize it and then pass it to an HttpURLConnection to POST.
protected void sendJson(final String play, final String prop) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the childThread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.44:80");
json.put("play", play);
json.put("Properties", prop);
StringEntity se = new StringEntity(json.toString());
se.setContentType(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();
showMessage("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Try this code:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.
Solution for Google Endpoints.
Request body must contains only JSON string, not name=value pair.
Content type header must be set to "application/json".
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String json ) throws Exception{
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(json.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
It sure can be done using HttpClient as well.
You can use the following code with Apache HTTP:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
response = client.execute(request);
Additionally you can create a json object and put in fields into the object like this
HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
For Java 11 you can use the new HTTP client:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
You can use publishers from InputStream, String, File. Converting JSON to a String or IS can be done with Jackson.
Java 11 standardization of HTTP client API that implements HTTP/2 and Web Socket, and can be found at java.net.HTTP.*:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("www.site.com"))
.header("content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
Java 8 with apache httpClient 4
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");
String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";
try {
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// set your POST request headers to accept json contents
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
// your closeablehttp response
CloseableHttpResponse response = client.execute(httpPost);
// print your status code from the response
System.out.println(response.getStatusLine().getStatusCode());
// take the response body as a json formatted string
String responseJSON = EntityUtils.toString(response.getEntity());
// convert/parse the json formatted string to a json object
JSONObject jobj = new JSONObject(responseJSON);
//print your response body that formatted into json
System.out.println(jobj);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I recomend http-request built on apache http api.
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);
int statusCode = responseHandler.getStatusCode();
String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null.
}
If you want send JSON as request body you can:
ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
I higly recomend read documentation before use.

Empty request when sending special characters to API with Java

I'm using Java to send http requests to my API which is created using Laravel (5.4). If I send a request without any special characters it all works like a charm. But if there are any 'special' characters like: é, å, ö and such the request in Laravel is empty:
dd(request()->all()) outputs []
I guess this has to do with some wrong settings while creating the request in Java. I couldn't find a solution.
Here is the code responsible for creating the request.
public class HttpClient {
org.apache.http.client.HttpClient client;
public HttpClient() {
client = HttpClientBuilder.create().build();
}
public void post(String json) {
try {
HttpPost request = buildPostRequest(json);
HttpResponse response = createClient().execute(request);
int code = getStatusCode(response);
if (code != 200) {
throw new Exception("Error (" + code + ") on server.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private org.apache.http.client.HttpClient createClient() {
return HttpClientBuilder.create().build();
}
private HttpPost buildPostRequest(String json) throws Exception {
HttpPost request = new HttpPost("some uri");
request.addHeader("Content-type", "application/json; charset=utf-8");
request.addHeader("Accept", "application/json");
StringEntity params = new StringEntity(json);
params.setContentEncoding("utf-8");
params.setContentType("application/json; charset=utf-8");
request.setEntity(params);
return request;
}
private int getStatusCode(HttpResponse response) {
StatusLine line = response.getStatusLine();
return line.getStatusCode();
}
}
EDIT
Dump of the request before it get's send to the API.
I found a solution to the problem. In the buildPostRequest() method I changed from a StringEntity to a ByteArrayEntity and coverted the string to UTF-8 bytes.
ByteArrayEntity params = new ByteArrayEntity(json.getBytes("UTF-8"));
If I send special characters to the API the request isn't empty anymore.
try this way
HttpPost request = new HttpPost(URLEncoder.encode("url here", "UTF-8"));

Nested JSON in URL request with Java

I'm attempting to nest JSON objects in the URL of a HTTP request to make use of an API. The raw JSON is
{
"jsonrpc":"2.0",
"id":"12345",
"params":{
"api_key": "e983322o",
"preset_id": "12345678",
"user_id": "3265999"
},
"method":"Tags.get"
}
(This is tested and works in a REST client)
And the method in Java is
private static void printSiteTags() {
try {
List<NameValuePair> params = new LinkedList<>();
params.add(new BasicNameValuePair("jsonrpc", "2.0"));
params.add(new BasicNameValuePair("id", "12345"));
params.add(new BasicNameValuePair("params[0]", new BasicNameValuePair("api_key", API_KEY).toString()));
params.add(new BasicNameValuePair("params[1]", new BasicNameValuePair("preset_id", "12345678").toString()));
params.add(new BasicNameValuePair("params[2]", new BasicNameValuePair("user_id", "3265999").toString()));
params.add(new BasicNameValuePair("method", "Tags.get"));
String rawUrl = addToUrl(SITE_URL, params);
//addToUrl just uses URLEncodedUtils
System.out.println(rawUrl);
URL url = new URL(rawUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
} catch (IOException e) {
e.printStackTrace();
}
}
The result of the raw URL is
[base site]?jsonrpc=2.0&id=12345&%5Bparams%5D%5Bapi_key%5D=e983322o&params%5B1%5D=preset_id%3D12345678&params%5B2%5D=user_id%3D3265999&method=Tags.get
(Which is obviously wrong)
Evidently, the response from the server is an error.
JSON should go into the request BODY.
And the request content-type should by application/json.
If you want to keep using URLConnection then have a look here for example:
POST request send json data java HttpUrlConnection
But note it doesn't matter which library you chose for formatting the json body, it's just a text - in your case {"jsonrpc":"2.0", "id":"12345",...
There are other approaches e.g. if you use httpClient, see example 8 in the following link:
http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.httpclient.methods.StringRequestEntity

I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported

Currently I'm using HttpClient, HttpPost to send data to my PHP server from an Android app but all those methods were deprecated in API 22 and removed in API 23, so what are the alternative options to it?
I searched everywhere but I didn't find anything.
I've also encountered with this problem to solve that I've made my own class.
Which based on java.net, and supports up to android's API 24
please check it out:
HttpRequest.java
Using this class you can easily:
Send Http GET request
Send Http POST request
Send Http PUT request
Send Http DELETE
Send request without extra data params & check response HTTP status code
Add custom HTTP Headers to request (using varargs)
Add data params as String query to request
Add data params as HashMap {key=value}
Accept Response as String
Accept Response as JSONObject
Accept response as byte [] Array of bytes (useful for files)
and any combination of those - just with one single line of code)
Here are a few examples:
//Consider next request:
HttpRequest req=new HttpRequest("http://host:port/path");
Example 1:
//prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();
Example 2:
// prepare http get request, send to "http://host:port/path" and read server's response as String
req.prepare().sendAndReadString();
Example 3:
// prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29 and read server's response as JSONObject
HashMap<String, String>params=new HashMap<>();
params.put("name", "Groot");
params.put("age", "29");
req.prepare(HttpRequest.Method.POST).withData(params).sendAndReadJSON();
Example 4:
//send Http Post request to "http://url.com/b.c" in background using AsyncTask
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
response=new HttpRequest("http://url.com/b.c").prepare(HttpRequest.Method.POST).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
}
}.execute();
Example 5:
//Send Http PUT request to: "http://some.url" with request header:
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it
HttpRequest req=new HttpRequest(url);//HttpRequest to url: "http://some.url"
req.withHeaders("Content-Type: application/json");//add request header: "Content-Type: application/json"
req.prepare(HttpRequest.Method.PUT);//Set HttpRequest method as PUT
req.withData(json);//Add json data to request body
JSONObject res=req.sendAndReadJSON();//Accept response as JSONObject
Example 6:
//Equivalent to previous example, but in a shorter way (using methods chaining):
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it
//Shortcut for example 5 complex request sending & reading response in one (chained) line
JSONObject res=new HttpRequest(url).withHeaders("Content-Type: application/json").prepare(HttpRequest.Method.PUT).withData(json).sendAndReadJSON();
Example 7:
//Downloading file
byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
FileOutputStream fos = new FileOutputStream("smile.png");
fos.write(file);
fos.close();
The HttpClient was deprecated and now removed:
org.apache.http.client.HttpClient:
This interface was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
means that you should switch to java.net.URL.openConnection().
See also the new HttpURLConnection documentation.
Here's how you could do it:
URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
IOUtils documentation: Apache Commons IO
IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar
The following code is in an AsyncTask:
In my background process:
String POST_PARAMS = "param1=" + params[0] + "&param2=" + params[1];
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL(Config.YOUR_SERVER_URL);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.i(TAG, "POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
} else {
Log.i(TAG, "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
Reference:
http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests
This is the solution that I have applied to the problem that httpclient deprecated in this version of android 22`
public static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String _url,Map<String,String> parameter) {
StringBuilder params=new StringBuilder("");
String result="";
try {
for(String s:parameter.keySet()){
params.append("&"+s+"=");
params.append(URLEncoder.encode(parameter.get(s),"UTF-8"));
}
String url =_url;
URL obj = new URL(_url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "UTF-8");
con.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(params.toString());
outputStreamWriter.flush();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + "\n");
}
in.close();
result = response.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally {
return result;
}
}
You are free to continue using HttpClient. Google deprecated only their own version of Apache's components. You can install fresh, powerful and non deprecated version of Apache's HttpClient like I described in this post: https://stackoverflow.com/a/37623038/1727132
if targeted for API 22 and older, then should add the following line into build.gradle
dependencies {
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}
if targeted for API 23 and later, then should add the following line into build.gradle
dependencies {
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:
useLibrary 'org.apache.http.legacy'
to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!
Which client is best?
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best
choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its
simple API and small size makes it great fit for Android...
Reference here for more info (Android developers blog)
You can use my easy to use custom class.
Just create an object of the abstract class(Anonymous) and define onsuccess() and onfail() method.
https://github.com/creativo123/POSTConnection
i had similar issues in using HttpClent and HttpPost method since i didn't wanted change my code so i found alternate option in build.gradle(module) file by removing 'rc3' from buildToolsVersion "23.0.1 rc3" and it worked for me. Hope that Helps.

Android, Java: HTTP POST Request

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
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("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
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("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

Categories