I need to use httpclient to connect to a webpage (Apache) running PHP scripts which is protected with .htaccess authentication.
I've been reading questions and answers (in here and other places) for an hour now, and none of the sultions is working for me. Either the methods people are using in classes like Base64.java does not exist, or the parameters are wrong.
I'm connecting to normal (non-protected webpages like this):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("date", cDate));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
But this, naturally, doesn't help when the page is protected. So how can I, in the easiest way, pass my username and password to the connection?
You can get a Base64 here: http://iharder.sourceforge.net/current/java/base64/.
I usually do something like following for authentication:
StringBuilder authentication = new StringBuilder().append("dogT4g").append(":").append("petTheDog5");
String result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
Hope that solves your problem.
Related
I use the following code to send data to my server:
public InputStream getStreamFromConnection(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
if(ConnectionDetector.isConnectedToInternet(this.context)) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} else {
return null;
}
}
When i now have a message in my params which looks like that:
The leadership earned 1000$ during the last years.
The server receives:
The leadership earned 1000
And all of the messages are cut exactly at the index of any special character.
And even more. if somone writes a message with a smile like:
:)
This arrives at the server
??
How can i send the special characters and smielies to the server?
It sounds like you just have to encode your URL before you execute a request with it.
Try encoding your URL like this:
String encodedUrl = URLEncodedUtils.format(urlWithParameters, "utf-8");
Do you have before your special characters this \\?
because without it the server won't understand it.
(Sorry I couldn't leave a comment due to reputation)
Here is how I use POST and it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
And I didnt know how to use PUT, so I got this code and I changed every "Post" to "Put"
but I dont think it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
When I try updating a user's account using this implementation ot PUT I get errors from the server. - "No session. Unauthorized."
When I use Chrome's postman with the same parameters, I get no problem, so I think my PUT implementation doesnt work.
You need to use the same DefaultHttpClient to make all the calls, because your session information is stored in the instance object.
If you need to use different instances, you may be able to do that getting the cookies from the login request and add them in the next requests using getCookieStore/setCookieStore.
I am trying to fetch current user info after making him log into his box, using the box sdk for android. In the box api documentation, they have mentioned everything using curls. I am not familiar with curl. So, can anyone please give me a java equivalent for this curl operation :
curl https://api.box.com/2.0/users/me-H "Authorization: Bearer ACCESS_TOKEN".
I have the users access token.So, please give me a java equivalent for the above curl operation.
You can use java HttpClient
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Authorization", "Bearer ACCESS_TOKEN"); // add headers if needded
//set params
BasicNameValuePair[] params = new BasicNameValuePair[] {new BasicNameValuePair("param1","param value"),
new BasicNameValuePair("param2","param value")};
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity( Arrays.asList(params), "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
//execute request
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity); //here response in string you can parse it
The HttpClient object that the other answer proposes is now deprecated. I solved a CURL problem like yours (with the extra difficulty of uploading a .wav file). Check out my code in this this answer/question. How to upload a WAV file using URLConnection
I am new to android networking and would like to find the best solution/source that would help me learn the same. I have a working android application but i want to include network services that can get and send data to the webserver. While i was searching for the same i found link ( http://www.helloandroid.com/tutorials/connecting-mysql-database ) which dont produce any results. I also found that SOAP or REST (with android) are probably recommended methods, if so please give complete tutorials to learn the same ( i have no prior knowledge on webservices). In my application I would be required to send data to the server and receive data from the servers sql
Thank you
This is for post data on server,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
// convert entity response to string
if (entity != null)
{
InputStream is = entity.getContent();
// convert stream to string
result = convertStreamToString(is);
result = result.replace("\n", "");
}
or see how to post data to remote server in android app [closed], Post the data to Server
I needed to send some XML to a webservices and I was able to do it with a normal StringEntity because it was just text but now I need to attach an image to it as well. I tried doing it with a MultipartEntity but I couldn't get it working with just the XML.
// Working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
HttpEntity entity = new StringEntity(writer.toString());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
// not working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
// no difference when removing the BROWSER_COMPATIBLE
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("xml", new StringBody(writer.toString()));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
And is there a way I could see the MIME that is being send?
You simply forgot:
httppost.setEntity(entity);
By the way, it's probably good form to set the Content-Type of your parts, e.g.:
entity.addPart("xml", new StringBody(writer.toString(),"application/xml",Charset.forName("UTF-8")));
As far as seeing what's being sent, see http://hc.apache.org/httpcomponents-client-ga/logging.html (especially "wire logging") for the HttpClient logging features, and
this question for how to get it working on Android.
Another way to see what's being sent is to set up your own "server" to receive the request. You can do this on a Unix-like system with netcat. The command-line
nc -l 1234
starts a server listening on port 1234, and will echo whatever is received.
If that "server" is on a machine 10.1.2.3, you can just use a new HttpPost("http://10.1.2.3:1234") to send the message there.
I have a similar problem but I'm sending the multipart with user/pass to a acegi security system, it works with this:
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
But not with this:
try {
for (NameValuePair param : params) {
multientity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(encoding))));
}
request.setEntity(multientity);
}