Parse Chinese characters with URLEncodedUtils in Java - java

I have a uri like
http://localhost/?name=foo&value=bar
And I use
org.apache.http.client.utils.URLEncodedUtils.parse(URI uri, String encoding)
to get a list of NameValuePairs, and it works nicely. But now I have need also the possibility to parse Chinese charecters, e.g.:
http://localhost/?name=生产者&value=单车
But URLEncodedUtilsparse fails to parse these characters correctly. How can I retrieve them and get a list of NameValuePairs again?

You can try like this:
String query1 = URLEncoder.encode("生产者", "UTF-8");
String query2 = URLEncoder.encode("单车", "UTF-8");
String url = "http://localhost/?name=" + query1 + "&value=" + query2;
Also check the java.net.URLEncoder

I faced the similar situation. URLEncodedUtils must be used with StringEntity. UrlEncodedFormEntity is broken.
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
URL);
List<NameValuePair> param_data = new ArrayList<>();
param_data.add(new BasicNameValuePair("name", [STRING_FOREIGN CHARS));
String s = URLEncodedUtils.format(param_data, java.nio.charset.Charset.forName("UTF-8"));
StringEntity entity = new StringEntity(s, java.nio.charset.Charset.forName("UTF-8"));
postRequest.setEntity(entity); // don't use postRequest.setEntity(new UrlEncodedFormEntity(param_data));
HttpResponse response = httpClient.execute(postRequest);
..[snipped] do whatever you want with response

Related

HTTP/1.1 400 Bad Request in java HTTP post

I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out ....
Here is my sample code:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. You are using colon (:) to separate keys from their values, but instead, the equal sign (=) must be used:
Wrong: "importFormatCode:1&data:" + params
Correct: "importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded)
Apart from that, you must not URL-encode the entire string but only the keys and the values. Otherwise you'll also encode the separator characters = and &!
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils (assuming that you're using Apache HTTP Components):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code

Servlet request.getParameter() always return null value

I'm working on simple client server communication using HttpPost. From the client side I'm setting a parameter(filename).
At the server side when I try to get the parameter value it's always showing null. I tried using MultiPartEntity but even that is not working.
Below is my client code:
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(dataFile), -1);
reqEntity.setContentType("binary/octet-stream");
// Send in multiple parts if needed
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
//setting the parameter
httppost.getParams().setParameter("filename", "xxxx.xml");
HttpResponse response = httpclient.execute(httppost);
int respcode = response.getStatusLine().getStatusCode();
And this is my servlet code:
response.setContentType("binary/octet-stream");
Scanner scanner = new Scanner(request.getInputStream());
// reading the parameter
String filename = request.getParameter("filename");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\" + filename)));
Kindly let me know any possible solution for this issue.
Thanks in advance!
Ur setting parameters wrong... at the client side, do this:
ArrayList<NameValuePair> postParameters = postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("filename", "xxxx.xml");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);

Get response Uri from apache HttpResponse and parse it (java)

I need to get the response uri from the HttpResponse and parse it into name-value pairs.
I need the analog for the following .NET fragment:
string authorizationRequestParameters = string.Format("client_id={0}&response_type=code&scope={1}&access_type=offline", ClientID, Scope);
Uri authorizationRequestUri = new Uri(OauthHost.AbsoluteUri + "?" + authorizationRequestParameters);
HttpWebResponse authorizationResponse = DoGet(authorizationRequestUri, cookies);
NameValueCollection authorizeResponseParameters = HttpUtility.ParseQueryString(authorizationResponse.ResponseUri.Query);
string callbackCode = authorizeResponseParameters["code"];
The necessary condition is, that in Java version DoGet method returns apache HttpResponse.
The way I tried to do this:
HttpResponse resp = hch.doGet("http://...?client_id=...&response_type=...&scope=...&access_type=...");
HttpEntity entity = resp.getEntity();
InputStream instream = entity.getContent();
System.out.print(IOUtils.toString(instream, "UTF-8"));
I can receive the html-content this way, but I need just response Uri, the part of it, that contains parameters.
How can I do that?
It seems like the HttpWebResponse.ResponseUri property comes from either a Content-Location header or it is a request URI. So something like this should work:
final String uri = "http://...?client_id=...&response_type=...&scope=...&access_type=...";
final HttpResponse resp = hch.doGet(uri);
final String contentLocation = resp.getFirstHeader ("Content-Location");
final String responseURI = contentLocation != null ? contentLocation : uri;

URL Illegal Character

Here is my code:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.d("URL", convertURL(URL));
request.setURI(new URI(URL));
HttpResponse response = client.execute(request);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
I don't know which error in my URL:
http://localhost/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1
I have already used a function to convert URL, but has not worked. But, if I trying open this URL in my Browser, it opens successfully.
Here is my error:
11-18 21:46:37.766: E/GetHttp(823): java.net.URISyntaxException: Illegal character in query at index 127: http://192.168.0.182/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1
There is a space in your URL, in position 127. The date is generated as "date_last=2012-11-18 09:46:37", which causes an error when opening the URL.
Spaces are not formally accepted in URLs, although your browser will happily convert it to "%20" or to "+", both valid representations of a space in a URL. You should escape all characters: you can replace space with "+" or just pass the String through URLEncoder and be done with it.
To use URLEncoder see e.g. this question: encode with URLEncoder only parameter values, not the full URL. Or use one of the constructors for URI which have a few parameters, not a single one. You are not showing the code that constructs the URL so I cannot comment on it explicitly. But if you have a map of parameters parameterMap it would be something like:
String url = baseUrl + "?";
for (String key : parameterMap.keys())
{
String value = parameterMap.get(key);
String encoded = URLEncoder.encode(value, "UTF-8");
url += key + "&" + encoded;
}
Some other day we can talk about why Java requires to set the encoding and then requires that the encoding be "UTF-8", instead of just using "UTF-8" as the default encoding, but for now this code should do the trick.
There is a whitespace character:
...2012-11-18 09:46:37... (at index 127, just like the error message says).
Try replacing it with %20
Do this way it will definetly help you
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/SendMessage");
try {
//Your parameter should be as..
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("messageText", msgText));
nameValuePairs.add(new BasicNameValuePair("senderUserInfoId", loginUserInfoId));
//set parameters to ur URL
myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute the connection
HttpResponse response = myClient.execute(myConnection);
}
catch (ClientProtocolException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}

How to use httpClient to filer parts of an xml file in Java

I am currently doing a project in which I have to request data from the metabolite database PubChem. I am using Apache's HttpClient. I am doing the following:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
HttpEntity entity = response.getEntity();
pubChemInchi = EntityUtils.toString(entity);
The problem is that this code streams the entire XML file:
<?xml version="1.0"?>
<PC-Compound
xmlns="http://www.ncbi.nlm.nih.gov"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.ncbi.nlm.nih.gov ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem.xsd">
etc.
What I want is that I can request, for example, the PubChem ID and it will paste the value that corresponds to that ID. I have found that this can be done with the native Java method, but I need to use the HttpClient for this.
With the native Java, it would be done like this:
cid = 5282253
reader = new PCCompoundXMLReader(
new URL("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + cid + "&disopt=SaveXML").newInputStream())
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
(Note: This piece of code was written in Groovy, but it also works in Java after some adjustments)
So, if anyone can help me out, that would be great:)
There are multiple ways to do this.
If you want to turn the response into a bean and dont expect the the structure of the response to change I'd look at using XStream.
Another option is using the SAX parser directly.
Ofcourse the quick and dirty approach is to turn your responses content into a bufferedReader. Then feed that reader into the XMLReader you are using.
An example using you code from above would be:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
cid = 5282253
reader = new PCCompoundXMLReader(br)
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
Googling for RESTful webservice clients or XMLReaders should give you plenty more information on this subject
Try using NameValuePair
For eg:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username", user123));
nameValuePairs.add(new BasicNameValuePair("password", pass123));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

Categories

Resources