Nested JSON in URL request with Java - 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

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.

How to pass a JSON string as a POST param avoiding character encoding in Java?

I'm trying to send a POST param to a REST endpoint I have. This param is a JSON String, that contains special chars like double quotes ("). On the endpoint I keep on getting the String encoded.
THis is the request part:
HttpClient client = HttpClientBuilder.create().build();
StringBuilder query = new StringBuilder();
query.append(callBackURL);
ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("update", "{\"object\":\"page\",\"entry\":[{\"id\":\"316492991876763\",\"time\":1417436403,\"changes\":[{\"field\":\"feed\",\"value\":{\"item\":\"comment\",\"verb\":\"add\",\"comment_id\":\"321528008039928_323256911200371\",\"parent_id\":\"316492991876763_321528008039928\",\"sender_id\":100006737955082,\"created_time\":1417436403}}]}]}"));
try {
HttpPost post = new HttpPost(query.toString());
post.setEntity(new UrlEncodedFormEntity(urlParameters));
post.addHeader("content-type", "application/json");
HttpResponse response = null;
try {
response = client.execute(post);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
catch (UnsupportedEncodingException e2) {
System.out.println(e2.getMessage());
}
Now in the endpoint part:
/**
* Callback method that receives FB updates
* #return 200 OK if everything goes OK, 401 ERROR otherwise
*/
#POST
#Path("/callback")
#Consumes(MediaType.APPLICATION_JSON)
public Response facebookUpdate(String update, #Context HttpServletRequest request, #Context HttpServletResponse response) throws ServletException, IOException{
JsonParser jsonParser = new JsonParser();
//parse it
JsonElement json = jsonParser.parse(update);
...
}
What I'm getting is a String encoded like this:
%7B%22object%22%3A%22page%22%2C%22entry%22%3A%5B%7B%22id%22%3A%22316492991876763%22%2C%22time%22%3A1417436403%2C%22changes%22%3A%5B%7B%22field%22%3A%22feed%22%2C%22value%22%3A%7B%22item%22%3A%22comment%22%2C%22verb%22%3A%22add%22%2C%22comment_id%22%3A%22321528008039928_323256911200371%22%2C%22parent_id%22%3A%22316492991876763_321528008039928%22%2C%22sender_id%22%3A100006737955082%2C%22created_time%22%3A1417436403%7D%7D%5D%7D%5D%7D
Something I cannot convert to a JsonElement...
Any ideas how to avoid this?
Thanks!
Alejandro
UPDATE:
I found what the problem was, so I'm explaining it here in case anyone has the same problem.
I was trying to pass a param using a BasicNameValuePair, like so:
ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("update", "{\"object\":\"page\",\"entry\":[{\"id\":\"316492991876763\",\"time\":1417436403,\"changes\":[{\"field\":\"feed\",\"value\":{\"item\":\"comment\",\"verb\":\"add\",\"comment_id\":\"321528008039928_323256911200371\",\"parent_id\":\"316492991876763_321528008039928\",\"sender_id\":100006737955082,\"created_time\":1417436403}}]}]}"));
I've changed to a simple StringEntity, like this:
StringEntity params = new StringEntity(json.toString());
HttpPost post = new HttpPost(query.toString());
Thus, I don't need to decode. Mistery remains on why passing an Array of BasicNameValuePair will encode the String...
use annotation above the method you want to produce JSON from
#Produces("application/json")

connecting to a php api from 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;
}

VIEWSTATE value in the HttpPost

Here is the case, I want to post to a website, but before that I must retrieve the viewstate value and then make the post using this value, but the problem is that viewstate value is changing every time i make posts, so I am a little confused how can I use it's value in the second post if the value on the server will be already different.
Is there any solution or am I doing everything wrong?
main with httppost
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(
"www.website.com/Login.aspx");
String viewstate = getViewState(client, request,
"www.website.com/Login.aspx");
System.out.println(viewstate);
request.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.setHeader("Content-Type", "text/html; charset=utf-8");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("__VIEWSTATE",
viewstate))
postParameters.add(new BasicNameValuePair("__EVENTTARGET", ""));
postParameters.add(new BasicNameValuePair("__EVENTARGUMENT", ""));
postParameters.add(new BasicNameValuePair("ctl00$tbUsername",
"name"));
postParameters
.add(new BasicNameValuePair("ctl00$tbPwd", "psw"));
postParameters.add(new BasicNameValuePair("ctl00$chkRememberLogin",
"0"));
postParameters
.add(new BasicNameValuePair("ctl00$cmdLogin", "Login"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String responseBody2 = EntityUtils.toString(response.getEntity());
System.out.println(responseBody2);
}
// print page wap
// System.out.println(responseBody2);
}
and then send httpget
String html = "";
try {
URL url1 = new URL("www.website.com/Login.aspx");
URLConnection conn = url1.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line+"\n");
}
rd.close();
html = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return findViewstate(html);
So what I was thinking, maybe I should reuse the same httpClient with the cookies or anything, so that the next request will be to the same page...
If I recall correctly ViewState values are encrypted by default and have information in them to prevent tampering, therefore, multiple requests WILL result in different values. But if you do a request, then make a post back to the page as the user would you should be ok, but you will need to make sure that all data goes back or you are going to hit issues with ASP.NET's event validation.

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