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();
}
Related
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
I am stuck on a uploading issue. Server is in dotnet. Here is my iPhone code:
-(NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
This works well, but when I am trying to upload by my Android app, it always returns error from server when there some special characters in url like (=).
See below the code:
Bitmap icon = BitmapFactory.decodeResource(this.contextParam.getResources(),
ByteArrayOutputStream bao = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("Data:", ba1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "dsfsdfsd"));
nameValuePairs.add(new BasicNameValuePair("filenamewithextension", "upload.png"));
nameValuePairs.add(new BasicNameValuePair("newfilename", "Testing upload"));
nameValuePairs.add(new BasicNameValuePair("entityid", "10"));
nameValuePairs.add(new BasicNameValuePair("filestream", ba1));
Log.i(TAG, httppost.getURI().toString());
Log.d(TAG, nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
String base64EncodedCredentials = Base64.encodeToString(CREDENTIALS.getBytes(), Base64.NO_WRAP);
httppost.addHeader("Authorization", "Basic " + base64EncodedCredentials);
httppost.addHeader("Content-Type", "application/largedata");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return getStringFromInputStream(response.getEntity().getContent());
} catch (ClientProtocolException e) {
Log.e(TAG, e.getLocalizedMessage());
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return responseString;
With above code server always returns with "Request Error". Why might this be happening?
Aside: I can't change the server implementation, I have to find a solution on the Android side.
I'm not 100% sure because you didn't post your log, but I had a similar issue with an App I was working on for iOS. For HTTP, they have encoding rules. You may need to "percent-escape encode" your HTTPPost.
For example:
www.website.com/security/authorizekey?url=www.website.com?user=bob
When the above link was used as my URL Post, the rules of HTTP truncated my Post so that the server only received "www.website.com/security/authorizekey?url=www.website.com?user=" and truncated my user "bob".
According to RFC 3986, the characters that should be permitted unescaped are the alphanumeric characters, plus "-", ".", "_", and "~":
2.3. Unreserved Characters
Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
See section 2 of the aforementioned RFC 3986 for more information.
Anyways, a solution might be similar to the following:
Potential Solution:
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
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
I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer
I'm trying to login into a website using java and jsoup. But every time I execute my post request I get an IOExeption. The website is www.seriecanal.com. I would appreciate it if someone could review the html form and tell me if I am creating the name-value pairs correctly and if there are any other obvious mistakes with the login. Here's my code:
public HttpResponse postData()
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://seriecanal.com/index.php?page=member");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//Get value of input "Regresa_web" because it changes each time i access the site
String Codigo_Fuente ="";
URL url = new URL("http://seriecanal.com/");
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente+line;
}
Document Doc = Jsoup.parse(Codigo_Fuente);
Element Regresa_WEb = Doc.getElementById("regresa_web");
String Valor_Regresa_Web = Regresa_WEb.attr("value");
//create name value pairs of the form
nameValuePairs.add(new BasicNameValuePair("_UserName", "userontheweb"));
nameValuePairs.add(new BasicNameValuePair("_Pwd", "123456789"));
nameValuePairs.add(new BasicNameValuePair("btnLogin", "Ingresar"));
nameValuePairs.add(new BasicNameValuePair("_submit_check", "1"));
nameValuePairs.add(new BasicNameValuePair("remember", "ON"));
nameValuePairs.add(new BasicNameValuePair("regresa_web", Valor_Regresa_Web));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse Response = httpclient.execute(httppost);
return Response;
}
catch (ClientProtocolException e)
{
return null;
}
catch (IOException e)
{
Log.i("ERROR", e.toString());
e.printStackTrace();
return null;
}
}
Stack:
04-21 13:42:04.206: D/dalvikvm(324): GC freed 15163 objects / 721152 bytes in 153ms
04-21 13:42:08.026: I/Resources(324): Loaded time zone names for en_US in 1863ms.
04-21 13:42:23.816: I/global(324): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
04-21 13:42:25.696: D/dalvikvm(324): GC freed 21866 objects / 1346160 bytes in 168ms
If you use fiddler or firebug you can interrogate the actual parameters that get sent. When I did this this is what I saw
_submit_check=1
btnLogin=Ingresar
password=test
remember=ON
username=test
It looks like you are sending the wrong params. The form input names do seem different to the ones being sent e.g. _UserName, but you never know if javascript is bound to the event and there is some additional magic going on there. As a result i always use firebug/fiddler.