Java HTTP-Request with POST-Data - java

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();
}

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.

Unable to post JSON data using HttpPost

I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"

Retrieve get response with Android

I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"

How should look the URL to GET the JSON String

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);

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.

Categories

Resources