Sorry, I don't speak English very well.
I try to send string "Nhập nội dung bình luận để gửi đi!".
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
String str ="Nhập nội dung bình luận để gửi đi!";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("file", str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
But I get "Nhập nội dung bình l" on my web server. How can I resolve it.
EDIT:
I encoded to UTF-8 by this code:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
replace by:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
but it still doesn't work.
Try this change:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
The server must also be able to handle UTF-8 for that to work.
Alternatively, if the text will be rendered as HTML, you can encode the whole thing so the server doesn't need to support UTF-8.
String str ="Nhập nội dung bình luận để gửi đi!";
That's html encoding, not URL encoding. Unfortunately Java doesn't include an html encoder as far as I know. You'd have to use a 3rd party library.
This thread lists a few libraries:
Is there a JDK class to do HTML encoding (but not URL encoding)?
Full hack using an example from that other thread. Try something like this...
public void post() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
String str ="Nhập nội dung bình luận để gửi đi!";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("file", encodeHTML(str)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
public static String encodeHTML(String s)
{
StringBuffer out = new StringBuffer();
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if(c > 127 || c=='"' || c=='<' || c=='>')
{
out.append("&#"+(int)c+";");
}
else
{
out.append(c);
}
}
return out.toString();
}
You need to encode the String with appropriate charset before sending to the web server. Otherwise, the String will be encoded in the default charset of the platform used. Check whether both server and program are using the correct charset to write and read the String
Say for example, it is UTF-8, Create String from ByteArray encoded with UTF-8 charset with code below
new String(YOUR_BYTE_ARRAY, Charset.forName("UTF-8"));
Reading the encoded String into ByteArray with same charset UTF-8 on the server side can be done as follows
YOUR_UTF8_STRING.getBytes("UTF-8");
Hope this clarifies!
Encode your url when sending from application:
// import java.net.URLEncoder;
str = URLEncoder.encode(str, "UTF-8");
And from the receiver decode the string:
// import java.net.URLDecoder;
str = URLDecoder.decode(str, "UTF-8");
Related
I have used the CloseableHttpClient APi for a Post call and Basic Auth for authorisation
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
MyJson myJson = new MyJson(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String param = gson.toJson(myJson);
StringEntity urlparam = new StringEntity(param);
String credentials = username + ":" + passwprd;
String base64Credentials = new String(Base64.getencoder().encode(credentials.getBytes()));
String authorizartionHeader = "Basic" + base64Credentials;
httppost.setHeader("Content-Type", "application/Json");
httppost.setHeader("Authorization", authorizartionHeader);
urlparam.setContentEncoding("UTF-8");
httppost.setEntity(urlparam);
httpclient.execute(httppost);
I am getting error
"Invalid UTF-8 middle byte"
I have encoded the JSON still the encoding is not working for other locales except English. How to encode the Post data.
I tried using the method
httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")) but I don't have any Namevaluepair and if the add the Username-pswd in that then getting Null pointer response.
You should try to set everything as UTF-8
StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);
And add proper header
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
In java while doing an HTTP post request using nameValuePairs we write the following code!
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sometesturl.com");
JSONObject json = new JSONObject();
json.put("id",1);
json.put("name","john");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", "abc"));
nameValuePairs.add(new BasicNameValuePair("samplejson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
As seen over here we use the UrlEncodedFormEntity to encode our request body. Similarly, I need to do the same in Javascript. I have seen the EncodeURIComponent method but that doesn't seem to encode the request body. Instead it encodes the URL.
Can someone tell me how to encode the request body in javascript?
Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);
I am trying to send a query url
String url = String.format(
"http://xxxxx/xxx/xxx&message=%s",myEditBox.getText.toString());
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httpclient.getCookieStore().addCookie(cooki);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
String response = httpclient.execute(httppost, responseHandler);
gives me error, illegal character at query. That's white space probably. How to deal with this issue?
Best Regards
You need to encode your url.
String query = URLEncoder.encode(myEditBox.getText.toString(), "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Can you try
httpclient.setRequestProperty("Accept-Charset","UTF-8");
url="http://xxxxx/xxx/xxx&message="+URLEncoder.encode(myEditBox.getText.toString(), "UTF-8");
Try .trim() while get value from edittext.
May be whitespace come from edittext and also use "utf-8".
see below code.
String value = URLEncoder.encode(myEditBox.getText.toString().trim(), "utf-8");
String url = "http://xxxxx/xxx/xxx&message=%s" + value;
I need to work with REST api in android application which is created by my client. Below text is just copied from the pdf the client provides us.
--
In this example, a new user is created.
The parts of a possible request to the server is shown below:
Message part Contents
Header POST {url-prefix}/rest/user
Content-Type: application/xml
Content-Length: 205
Body <request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
--
After searching and studying, I come to know that, the possible request code (in Java) might be:
URL url=new URL("http://api.example.com/rest/user/?name=myUserName&password=myUserPassword&groupId=12345");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("Post");
OutputStreamWriter out=new OutputStreamWriter(conn.getOutputStream());
out.write("respose content:");
out.close();
From the pdf manual they provide, I got to know, for every request to the server, the client (thats me) has to transmit the authentication data.
My question is, where do I put the authentication data in the query string? Please help me on this.
Edit:After posting the below code as request:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.example.com/rest/user/?name=Foysal&password=123456&groupid=12345");
httpPost.addHeader("Accept", "text/xml");
httpPost.setHeader("Content-Type","application/xml;charset=UTF-8");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", "APIappDevAccount"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
httpClient.setParams(params);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf;
int ByteRead;
buf = new byte[1024];
String xmldata = null;
double totalSize = 0;
while ((ByteRead = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, ByteRead);
totalSize += ByteRead;
}
xmldata = os.toString();
os.close();
is.close();
But I got the response as:
404
Not Found
Not Found The requested
URL /rest/user/ was not found on this
server. Apache/2.2.6
(Fedora) DAV/2 mod_ssl/2.2.6
OpenSSL/0.9.8b Server at
api.example.com Port 80
Looks to me like they want you to POST an XML document and put the authentication in that. Not much of a REST API (most REST APIS don't require an XML document).
You need to use conn.getOutputStream() to send that doc to the server and use conn.getInputStream() to read the response.
So you would have to create the XML doc like the one they show:
<request>
<client>
<id>XY</id>
<name>myName</name>
<password>myPassword</password>
</client>
<user>
<name>myUserName</name>
<password>myUserPassword</password>
<groupId>12345</groupId>
</user>
</request>
And then send it in your POST:
conn.setRequestProperty ( "Content-Type", "text/xml" );
out.write(requestDoc); //where requestDoc is the String containing the XML.
out.flush();
out.close();
You may execute a POST request like shown here: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient and put the authentication data as name value pairs:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "myUserName"));
nameValuePairs.add(new BasicNameValuePair("password", "myUserPassword"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// ... handle exception here
}