This is my code . I am trying to do a post on the rest Api from android (API 10)
HttpPost httpPost = new HttpPost(
"http://www.reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/RESTfulWS/queryHitPathways");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type"," text/plain; charset=UTF-8");
httpPost.addHeader("","PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1");
try {
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
System.out.println(statusCode);
Log.e(Gsearch.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
I just don't know what to add (as the first string)in the last addHeader method ! I tried "name", "ID" etc. Its not listed in the API too. The API documentation is here : http://reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/ReactomeRESTFulAPI.html
I tried to use firebug to see the post request in browser but it says post data = "PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1" .
Right now I am using "body" in there and I am getting a json respnse of length 0 . But if i try on browser from the documentation link , I get a json response. so the error is in the addHeader part.
The problem is your assumption that the data should be part of the header, because it shouldn't. If I run the sample request from the API through a random webproxy, I can see the following headers:
POST /ReactomeRESTfulAPI/RESTfulWS/queryHitPathways HTTP/1.1
Host reactomews.oicr.on.ca:8080
Content-Length 41
Accept application/json
Origin http://reactomews.oicr.on.ca:8080
User-Agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-type text/plain
Referer http://reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/ReactomeRESTFulAPI.html
Accept-Encoding gzip,deflate,sdch
Accept-Language nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.3
In other words: none of the "PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1" strings are there. In stead, that data is part of the post body, or the 'entity' that you can set to the post method.
Something like this should probably do it:
// creating of HttpPost omitted
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type"," text/plain; charset=UTF-8");
StringEntity entity = new StringEntity("PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1");
httpPost.setEntity(entity);
// execute post and get result etc.
Related
I need to send string (vietnamese) from Android devices to server like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.URL.UPDATE_CURRENT_STATUS);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", "Thạch thất Hanoi "));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int respnseCode = response.getStatusLine().getStatusCode();
if (respnseCode == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But when server gets the string, its not like
Thạch thất Hanoi
its become
Thạch Thất Hanoi
My code in server side:
#RequestMapping(value = "/UpdateCurrentStatus", method = RequestMethod.POST, produces = { "application/json" })
#ResponseBody
public MessageDTO updateCurrentStatus(
#RequestParam Map<String, String> requestParams) throws TNException {
String location = requestParams.get("location");
System.out.println(location);
MessageDTO result = driverBO.updateCurrentStatus(location);
return result;
}
How can I resolve this problem? Thank you.
Did you set you android httpclient Content-Type header to application/json; charset=utf-8 instead of "application/json"?
I think your problem is that the content entity location you sent is encoded correctly in UTF-8 but server failed to acknowledge UTF-8. clarify it in Content-Type header.
You can diagnose http content and its header with great http monitoring tool Fiddler.
-EDIT BELOW-
Relace your UrlEncodedFormEntity as below. Set header to application/json; charset=utf-8 as I described earlier. it's good to set it up still.
JSONObject jsonParam = new JSONObject();
jsonParam.put("location", "Thạch thất Hanoi ");
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
httppost.setEntity(entity);
I am trying to make an HttpPost with multiPart/form-data via my android app. I have a postman test that is working with my api and the preview of that request in postman, looks like this:
POST /api/0.1/content/upload HTTP/1.1
Host: 54.221.194.167
X-AUTHORIZATION: 166e649911ff424eb14446cf398bd7d6
Cache-Control: no-cache
Postman-Token: 2412eba9-f72d-6f3b-b124-6070b5b26644
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file01"
{"mime_type":"image/jpeg","title":"IMG_20140131_111622"}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file01"; filename="addedaslib.jpg"
Content-Type: image/jpeg
----WebKitFormBoundaryE19zNvXGzXaLvS5C
I am trying to replicate that using the multipart/form-data with my android HttpPost but it doesn't seem to be working. Is there a way to "preview" my request and see how it is actually posting to the api? what am i doing wrong? my code:
public HttpResponse invokeXAUTHPOSTService(String url, String token, File file) {
client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpResponse response = null;
MultipartEntity mpe = new MultipartEntity();
try {
Log.v("API", "URL:"+url);
request.setHeader("Content-Type", "multipart/form-data");
request.addHeader("X-AUTHORIZATION",token);
request.addHeader("Cache-Control", "no-cache");
DRPContentForUpload content = new DRPContentForUpload(file);
String jsonObject = DRPJSONConverter.toJson(content);
FormBodyPart part1= new FormBodyPart("file01", new StringBody(jsonObject));
FormBodyPart part2= new FormBodyPart("file01", new FileBody(file));
mpe.addPart(part1);
mpe.addPart(part2);
//
request.setEntity(mpe);
Log.v("RAW REQUEST", "request looks like:"+mpe.toString());
response = client.execute(request);
EDIT
I was able to talk to my API team, and they said my post actually looks like this:
--0ieMJK6PPwcrM_K3KQvl6eNDGqooZPzJcvHOm0
Content-Disposition: form-data; name="file01"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit
{"mime_type":"image/jpeg","title":"IMG_20140131_111622"}
--0ieMJK6PPwcrM_K3KQvl6eNDGqooZPzJcvHOm0
Content-Disposition: form-data; name="file01"; filename="IMG_20140131_111622.jpg"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
That said its still not working and spitting back an error that i am missing params
here is a screen shot of the libraries included in my project:
So after searching high and low for an answer, and almost giving up, this link finally helped
here is the final working code:
public HttpResponse invokeXAUTHPOSTService(String url, String token, File file) {
client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpResponse response = null;
DRPContentForUpload content = new DRPContentForUpload(file);
String jsonObject = DRPJSONConverter.toJson(content);
String BOUNDARY= "--eriksboundry--";
request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
request.addHeader("X-AUTHORIZATION",token);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY,Charset.defaultCharset());
try {
entity.addPart("file01", new StringBody(jsonObject));
entity.addPart("file01", new FileBody(file));
request.addHeader("Accept-Encoding", "gzip, deflate");
} catch (UnsupportedEncodingException e) {
Log.v("encoding exception","E::: "+e);
e.printStackTrace();
}
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
request.setEntity(entity);
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
Is the problem that the mime-type for your image isn't being set properly? Try to use the alternative constructor for FileBody:
FormBodyPart part2 = new FormBodyPart("file01", new FileBody(file, "image/jpeg"));
Giving both parts of the multi-part request the same name is a bit suspicious, but it doesn't seem to be causing you problems here.
If you want to see what your body looks like before sending, try using EntityUtils.toString(Entity) on the multi-part entity after adding all of the elements. The image is simply binary so won't print very well, but the headers should be readable.
I am using http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java for Android.
I set the response using the following code:
HttpResponse getResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
getResponse.setEntity(new StringEntity(new String("The requested resource " + target + " could not be found due to mismatch!!")));
conn.sendResponseHeader(getResponse);
conn.sendResponseEntity(getResponse);
My response in Mozilla Poster or browser has the header 404 and the response body as:
The requested resource could not be found due to mismatch!!HTTP/1.1 200 OK
How can I get only the HTTP body String? Why am I getting HTTP/1.1 200 OK in response. I dont set this in my code. Any help is appreciated.
this might help you...
i think response is what you need
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
there was a problem in my defined handle() method. I was creating a new HttpResponse for each request instead of using the response passed in the
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
I'm working on a project in which I need to get some data from my app engine server which contains hebrew characters (the data is sent in json).
On server side:
resp.setHeader("Content-Type", "application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
out.print(responeData.toString());
when I'm debugging the server I see that the response data seems fine (meaning, it's showing my hebrew characters.
On the client side (android):
After executing this code, the resultData i'm getting is with ??? instead hebrew characters.
I tried all different encodings such as 'windows-1255', 'iso-8859-8'
Does anyone knows what the problem is?
Thanks!
// Create new default http client
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout Limit
HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(serviceURL);
try {
StringEntity se = new StringEntity(requestPayload.toString());
post.addHeader(CustomHeader.TASK_NAME.getHeaderName(), taskName);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
// Execute the request
response = client.execute(post);
// Get the response status code
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
if (response != null) { // Checking response
InputStream in = response.getEntity().getContent(); // Get the data in the entity
retreturnVal = HttpCaller.readContentFromIS(in);
}
}
} catch (Exception e) {
Log.e("Error in connectivity layer, stacktrace: ", e.toString());
return null;
}
public static String readContentFromIS(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"), 8);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
Assuming you are using a ServletResponse on your server, instead of calling
resp.setHeader("Content-Type", "application/json; charset=UTF-8");
you should call
resp.setContentType("application/json; charset=UTF-8");
This should have the effect of changing the encoding used in the call to getWriter() to UTF-8. I don't think that calling setHeader has the same side effect.
I had the same problem but I did
StringEntity se = new StringEntity(requestPayload.toString(), "UTF-8");
instead of
StringEntity se = new StringEntity(requestPayload.toString());
and it works fine for me, it's another solution.
I am trying to build a small application in which the application will communicate with a php script with the help of JSON objects. I successfully implemented the GET Request test application but using JSON with post is creating problems. The code generates no error but my php script reply with no nothing except an empty Array() which implies that nothing was sent over the connection with code:
<?php print_r($_REQUEST); ?>
and trying with
<?php print($_REQUEST['json']); ?>
throws HTML back to the application with json variable not found error.
I have already tried a few solutions mentioned here including: How to send a JSON object over Request with Android? and How to send a json object over httpclient request with android so it would be great if you can point out my mistake and can briefly describe what exactly I was doing wrong. Thanks.
Here is the code snippet for from where the JSON Object is converted into string and then attached to a Post variable.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppostreq.setEntity(se);
//httppostreq.setHeader("Accept", "application/json");
//httppostreq.setHeader("Content-type", "application/json");
//httppostreq.setHeader("User-Agent", "android");
HttpResponse httpresponse = httpclient.execute(httppostreq);
HttpEntity resultentity = httpresponse.getEntity();
Here is TCP Stream Dump collected through wireshark if it can help:
POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
[test] => true
)
Test // echo statement left intentionally.
you are using PHP on the server side, so your HTTP entity must be a multipart encoded one. See this link. You are using a string entity, but this is not correct. It must be a MultipartEntity, which emulates what the browser does when you submit a form in a web page. MultipartEntity should be in httpmime jar.
Once you have your multipart entity, simply add a Part named "json", and set its contents to the string representation of your json-encoded object.
Note that this answer is because you use PHP on the server side, so you must use its "protocol" to read variables via $_REQUEST. If you used your own request parser oh the server side, even a StringEntity could be ok. See HTTP_RAW_POST_DATA
The below should work. Make sure to set the appropriate keys for what your form post is expecting at the top. Also I included how to send an image as well as other various json data, just delete those lines if that is not necessary.
static private String postToServerHelper(
String action,
JSONObject jsonData,
byte[] imageData){
// keys for sending to server
/** The key for the data to post to server */
final String KEY_DATA = "data";
/** The key for the action to take on server */
final String KEY_ACTION = "action";
/** The return code for a successful sync with server */
final int GOOD_RETURN_CODE = 200;
/** The key for posting the image data */
final String KEY_IMAGE = "imageData";
/** The image type */
final String FILE_TYPE = "image/jpeg";
/** The encoding type of form data */
final Charset ENCODING_TYPE = Charset.forName("UTF-8");
// the file "name"
String fileName = "yourFileNameHere";
// initialize result string
String result = "";
// initialize http client and post to correct page
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php");
// set to not open tcp connection
httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
// build the values to post, the action and the form data, and file data (if any)
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try{
multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE));
multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE));
if (imageData != null){
multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName));
}
}catch (Exception e){
return e.getMessage();
}
// set the values to the post
httpPost.setEntity(multipartEntity);
int statusCode= -1;
// send post
try {
// actual send
HttpResponse response = client.execute(httpPost);
// check what kind of return
StatusLine statusLine = response.getStatusLine();
statusCode = statusLine.getStatusCode();
// good return
if (statusCode == GOOD_RETURN_CODE) {
// read return
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
content.close();
result = builder.toString();
// bad return
} else {
return String.parse(statusCode);
}
// different failures
} catch (ClientProtocolException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
// return the result
return result;
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject clientList = new JSONObject ();
clientList.put("name","");
clientList.put("email","");
clientList.put("status","");
clientList.put("page","");
JSONObject listclient = new JSONObject ();
listclient.put("mydetail", clientList);
//--List nameValuePairs = new ArrayList(1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", tokenid));
nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("JSON",nameValuePairs.toString());
//-- Storing Response
HttpResponse httpResponse = httpClient.execute(httpPost);