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
Related
I'm attempting to get a json string back from an HTTP post request in my andorid app. Using a solution from this post, code also shown here.
public void post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
httpClient.execute(httpPost);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I call post from inside of an Async Task (using to handle network access on a separate thread).
String result;
result = post("https://StringURLGoesHere.com/", "jsonStringBodyGoesHere");
According to the documentation for HttpClient class, to handle the response, I need to add a second parameter ResponseHandler to the HttpClient.execute() method.
public interface ResponseHandler<T> {
T handleResponse(HttpResponse var1) throws ClientProtocolException, IOException;
}
I did as such:
public String post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
ResponseHandler<String> reply = new ResponseHandler<String>() {
#Override
public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
return httpResponse.toString();
}
};
return httpClient.execute(httpPost,reply);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I show the string in a textview on my application. It reads:
org.apache.http.message.BasicHttpResponse#1446ef0c
or
org.apache.http.message.BasicHttpResponse#b83bd3d
or
org.apache.http.message.BasicHttpResponse#1c4c9e1d
and so on.
Why am I getting this return as a string? What should change in order to get the string of the json object returning after the post?
Try like below to capture HttpRepose to see your response;
HttpClient request = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
get.setHeader( "Authorization", token);
HttpResponse response = null;
try {
response = request.execute( get );
} catch ( ClientProtocolException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
StringBuffer result = new StringBuffer();
String line = "";
while ( (line = rd.readLine()) != null ) {
result.append( line );
}
System.out.println( response.getStatusLine().getStatusCode() );
System.out.println( result.toString() );
You could do like this:
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString; //this is your want
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.
My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
My web service code is following i am using WCF Restful webservices,
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Login?parameter={parameter}")]
string Login(string parameter);
public string Login(string parameter)
{
/*
* input := {"username":"kevin","password":"123demo"}
* output:= 1=sucess,0=fail
*
*/
//Getting Parameters from Json
JObject jo = JObject.Parse(parameter);
string username = (string)jo["username"];
string password = (string)jo["password"];
return ""+username;
}
my client side(Android) code is following
JSONObject json = new JSONObject();
try {
json.put("username","demo");
json.put("password","password123");
HttpPost postMethod = new HttpPost(SERVICE_URI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
HttpClient hc = new DefaultHttpClient();
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception", ""+e);
}
I am getting following output after calling Web service:
The server encountered an error processing the request. See server
logs for more details.
Basically my problem is I am unable to pass value by using NameValuePair.
Following code worked for me:
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
}
return string;
}
I'm new to http file transfer. I want to send a file from android sdcard to server. For that i tried the below code. I converted the bytes to json string and sent it to the server. But I'm unable to receive it on the server side. I'm using jsp on server side. But there should be some efficient way to do this. Please provide me some ideas.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
jsp
<%
String value = request.getParameter("wavfil");
byte[] wavByte = value.getBytes();
FileOutputStream fos = new FileOutputStream("/TESTFILE.wav");
fos.write(wavByte, 0, wavByte.length);
if (wavByte != null) {
out.println("Success");
} else {
out.println("Failed");
}
%>
Add below lines
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.x.x.x:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Create and attach file to the Post
File file = new File("pathto your file"); //replace with actual path
MultipartEntity entity = new MultipartEntity();
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
entity.addPart("file", new FileBody(file));
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}