I would like to do a HTTP post request from my virtual android device on the hostmachine.
Below you'll see an image on how I post, by using the old WebFetch tool.
I don't know what URL to use for calling the hostmachine?
I got no idea how my body string can be used an input?
Does anybody have an idea on how to solve this?
If you want to connect to the computer which is running the Android simulator, use the IP address 10.0.2.2. You can read more about it here.
Also check out the accepted answer in following question to see how json can be send as post data:
How to send POST request in JSON using HTTPClient?
you can use following code to make HTTP get request:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://10.0.2.2:port/your_path_with_parameter";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
Related
I had tried to acess to GitHub via Java to get the latest release of a repository and I had found this and I tried to use it with this code:
String url = "https://github.com/:owner/:repo/releases/latest";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
request.addHeader("content-type", "application/json");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
and the only thing I get as response is the HTML code of the website but I want the json response like you can see in the exaple response here.
Thanks for the Help!
Yea, it is right, you have to acess to api.github.com and you have to set Accept: application/vnd.github.v3+json
So I have a json string I'm trying to send to a local server. The code I'm using to post it is:
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://localhost:13000");
StringEntity params =new StringEntity(jsonCont.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
And then I have a Nodejs server running express to listen for the post:
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
app.post('*', function (request, response) {
console.log(request);
response.send("200");
});
app.listen(13000, function () {
console.log("Started on PORT 13000");
})
My issue is that the server is just printing empty json strings (e.g {}), and not the json string I sent it. (The Java code is returning 200 success)
I'm assuming I'm doing something wrong here, but what?
Since you are posting json, you should use json middleware for body-parser
app.use(bodyParser.json());
Try bodyParser.json() instead of bodyParser.urlencoded().
I am in a ditch since last few days trying out to get this,but not able to bring out any desired results.I will try to make myself clear that what i am looking for in following points:
I am working on android app,that will update the location of the user on the server using servlets(on my localhost).There is no problem regarding this,all is working fine.
The real problem that came in my way was when i was trying to get response from server back to android device,i just want to return a simple string,or something like that,Most likely a parameter,that will be utilized by the android app.Then i came to know about the json thing that i have to use it for doing what i am looking for.I have searched a lot about it,found some code too,but not able to use it well,
So my questions are
Is it possible to retrieve response from the servlet,and extract the required values from it without using json or any parsing technique,because i needed something like a single string only.
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet();
URI address=new URI("http://xxx.xxx.xxx.xxx:8080/MyServlet");
request.setUri(address);
HttpResponse response=client.execute(request);
The code from the android device requesting the response and the servlet are shown above,however when i call the toString method on response.toString() in android device,it yield me a string with some sequence of numbers,which are of no use to me.
HELP! HELP! HELP!
A simple example of it might help me up,
You could use a servlet that generates plain text result without any encoding technique.
On the server side, just replace your doGet function to look like that:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
On the client side, you could use the following code:
try {
final HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://SERVLET_URL/");
HttpResponse response = httpClient.execute(httpGet);
final HttpEntity entity = response.getEntity();
Log.i(TAG, "Servlet Result: " + EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException", e);
} catch (ParseException e) {
Log.e(TAG, "ParseException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
I am still a little skeptical as to how to connect my Android app to a PHP script. I saw somewhere that the following code will connect the app to the server. But I am new at android so I do not know how to really use it.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://url.to.my.app.com");
HttpResponse response = httpClient.execute(httpGet);
// handle response'
I understand that this opens a connection to an online server, but what I do not understand is what kind of response is returned by the server and how to process it. Also, I want to know how to send data through POST to the server from my app.
(If you could provide some code of your own, that would be helpful too) Thanks!
This will open a connection and send a http GET request to server. Your PHP script executes on the server side for this request and returns some contents. You can use folowing code to process the response.
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
}
For POST execution you need to do something like this.
// 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> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("test1","test1" ));
nvps.add(new BasicNameValuePair("test2", "test2" ));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// 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 use GET method to connect to the server, and the server responses http status code 403.
When I paste the url of my GET method to browser, I'm received "some text" and http status code 403. But when I send a GET request with the same url to the server by HttpURLConnection of Java(Android), I'm just received http status code 403, and response text is null.
So anyone can tell me how to get the "some text" when server return code 403.
Thanks in advance.
Just do as Zoombie wrote and add line:
String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
If it doesn't work, your server doesn't set the reason. Then you should map codes to standard reason phrases:
List of HTTP status codes
Try to use DefaultHttpClient class,
client = new DefaultHttpClient(httpParameters);
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}