How should look the URL to GET the JSON String - java

Why with first String the "jsonGetMethod" method works, but with second and third Strings - does not? When I'm inputting the URL from all the Strings in Android Web-Browser - I see the json response. (I'm using Eclipse, Real Android Device(not emulator) connected by Wi-Fi to internet, in the AndroidManifest Internet Permission is added.)
//This String works fine
private static String url = "http://json-ld.org/contexts/person.jsonld";
//Log.d(jsonStr) shows "null"
private static String url = "http://192.168.1.200:8080/test/json";
//Exception throws
private static String url = "192.168.1.200:8080/test/json";
public String jsonGetMethod(String url)
{
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
String jsonStr = jsonGetMethod(url);
Log.d(jsonStr);

Related

JSON Post Request contains no parameters

I have a problem by my json post request. I created a JsonObject and want to post it to the server but the body of the post request which is received by the server contains nothing and I don't know why...
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
String contentType = "application/json";
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "your name");
jsonObj.put("message", "your message");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
Provide "Content-Type" header to request with value "application/json". It seems server can't found proper message body mapper.

How to convert curl code into java

I am new in android and java I want to get access data from this API.
All we need to do convert this into java code
curl --include --header "X-Access-Token: YOUR_API_TOKEN_HERE" "http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0"
Your given API has a header and basic GET format. This can be converted in Java easily.
See the code example,
public String httpGet(String s, String api_token) {
String url = s;
StringBuilder body = new StringBuilder();
httpclient = new DefaultHttpClient(); // create new httpClient
HttpGet httpGet = new HttpGet(url); // create new httpGet object
httpGet.setHeader("X-Access-Token", api_token);
try {
response = httpclient.execute(httpGet); // execute httpGet
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// System.out.println(statusLine);
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection(); // stop connection
}
return body.toString(); // return the String
}
Now call the function and pass the url along with your header API token,
httpGet("http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0", YOUR_API_TOKEN)

How to send a Json to a web service using HttpPost

Hi I want to send a json object to a web service , I have tried almost everything without success. When the webservice recives the data it returns "eureka" , so I want to be able to see the response too.
public void sendData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=");
try {
httppost.setEntity(new UrlEncodedFormEntity(json));
// 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
}
}
private void SendBookingData(final String SendCustomerId,final String SendCustomerName, final String BookingDate,
final String BookingTime, final String SendNetAmount,final String SendTotalAmount, final String SendTotalQuantity,
final String SendDeliveryDate, final String GetBranchId,final String Senduserid,final String Sendratelistid) {
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
String SendBookingURL= "your url";
HttpPost post = new HttpPost(SendBookingURL);
HttpResponse response;
json.put("GetcustomerName", SendCustomerName);
json.put("GetBookingDate",BookingDate);
json.put("GetTotalCost", SendTotalAmount);
json.put("GetNetAmount", SendNetAmount);
json.put("GetTotalQuantity",SendTotalQuantity );
json.put("GetCustomerId", SendCustomerId);
json.put("GetDeliveryDate", SendDeliveryDate);
json.put("GetBookingtime", BookingTime);
json.put("GetBranchId", GetBranchId);
json.put("GetUserId", Senduserid);
json.put("GetRateListId", Sendratelistid);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
try {
response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity != null) {
ResponseSummaryTable = EntityUtils.toString(entity);
System.out.println("body" + ResponseSummaryTable);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Send string entity instead
CODE:
HttpClient client = new DefaultHttpClient();
HttpUriRequest request;
request = new HttpPost(<-URL->);
StringEntity entity = new StringEntity(<-Your JSON string->);
((HttpPost) request).setEntity(entity);
((HttpPost) request).setHeader("Content-Type",
"application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
This code will send json as string entity to server and receives HttpEntity as response

HTTPResponse's string from Play is empty

I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.

Java HTTP-Request with POST-Data

I wrote the following code in java to send some data via POST-Variables to a PHP-File of my website and then I want to get the source code of this website.
public DatabaseRequest(String url, IDatabaseCallback db_cb)
{
this.db_cb = db_cb;
site_url = url;
client = new DefaultHttpClient();
request = new HttpPost(site_url);
responseHandler = new BasicResponseHandler();
nameValuePairs = new ArrayList<NameValuePair>(0);
}
public void addParameter(List<NameValuePair> newNameValuePairs)
{
nameValuePairs = newNameValuePairs;
}
public void run()
{
db_cb.databaseFinish(getContent());
}
public String[] getContent()
{
String result = "";
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
result = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] result_arr = result.trim().split("<br>");
for (int i = 0; i < result_arr.length; i++)
{
result_arr[i] = result_arr[i].trim();
}
return result_arr;
}
When I want to run this code, then eclipse throws the following error message:
Try this:
// executes the request and gets the response.
HttpResponse response = client.execute(httpPostRequest);
// get the status code--- 200 = Http.OK
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity httpEntity = response.getEntity();
responseBody = httpEntity.getContent();
if (statusCode = 200) {
// process the responseBody.
}
else{
// there is some error in responsebody
}
EDIT: To handle UnsupportedEncodingException
Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.
// Url Encoding the POST parameters
try {
httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}

Categories

Resources