Help setting cookie to HttpClient
Created a program which logins to an external web service. However, to obtain vital information from
an HTTP GET, I am unable to pass in the cookie (generated from the login).
public class ClientHelper {
private final static String PROFILE_URL =
"http://externalservice/api/profile.json";
private final static String LOGIN_URL = "http://externalservice/api/login";
public static Cookie login(final String username, final String password) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(LOGIN_URL);
HttpContext localContext = new BasicHttpContext();
client.getParams().setParameter("http.useragent", "Custom Browser");
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
List<Cookie> cookies = null;
BasicClientCookie cookie = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user", username));
nameValuePairs.add(new BasicNameValuePair("passwd", password));
UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post, localContext);
cookies = client.getCookieStore().getCookies();
System.out.println(cookies.get(1));
cookie = new BasicClientCookie(cookies.get(1).getName(), cookies.get(1).getValue());
cookie.setVersion(cookies.get(1).getVersion());
cookie.setDomain(cookies.get(1).getDomain());
cookie.setExpiryDate(cookies.get(1).getExpiryDate());
cookie.setPath(cookies.get(1).getPath());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
catch (Throwable e) {
e.printStackTrace();
}
return cookie;
}
public static void getProfile(Cookie cookie) {
DefaultHttpClient client = new DefaultHttpClient();
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie);
client.setCookieStore(cookieStore);
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet get = new HttpGet(PROFILE_URL);
HttpResponse response;
try {
response = client.execute(get, context);
BufferedReader rd =
new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
App.java (class that uses ClientHelper):
public class App {
private static final String USER = "myusername";
private static final String PASSWD = "mypassword";
public static void main(String[] args) {
Cookie cookie = ClientHelper.login(USER, PASSWD);
ClientHelper.getProfile(cookie);
}
}
When I run App, I am able to login (I see the generated JSON) but the getProfile() method returns an empty JSON object:
{}
From the command line, using curl I am trying to emulate this:
curl -b Cookie.txt http://externalservice/api/profile.json
This actually works but not my Java program.
Try by executing this part of the code:
List<Cookie> cookies = client.getCookieStore().getCookies();
for (Cookie cookie : cookies) {
singleCookie = cookie;
}
After
HttpResponse response = client.execute(post, localContext);
After changing your code to get the cookies after the login request, you actually are getting all the cookies from the request.
I suspect the problem is that whatever Cookie it is at index 1 in the CookieStore isn't the one you need, and obviously since it's not throwing an IndexOutOfBounds exception when you do that, there's at least one other Cookie in there (at index 0). Return the list of cookies and send all of them with your profile request.
Taking your code, changing all those indexes from 1 to 0 and pointing at this simple PHP script shows that it is receiving then sending the cookies:
<?php
setcookie("TestCookie", "Some value");
print_r($_COOKIE);
?>
output:
[version: 0][name: TestCookie][value: Some+value][domain: www.mydomain.org][path: /][expiry: null]
Array
(
)
Array
(
[TestCookie] => Some value
)
I figured it out... I was creating two different HTTP clients instead of using the same one.
#Brian Roach & Raunak Agarwal thank you both very much for the help!
Here's the fix:
public static HttpClient login(final String username, final String password)
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(LOGIN_URL);
client.getParams().setParameter("http.useragent", "Custom Browser");
client.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user", username));
nameValuePairs.add(new BasicNameValuePair("passwd", password));
UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader reader =
new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (Throwable e) { e.printStackTrace(); }
return client;
}
public static void getProfile(HttpClient client)
{
HttpGet get = new HttpGet(PROFILE_URL);
HttpResponse response;
try
{
response = client.execute(get);
BufferedReader reader =
new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (ClientProtocolException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
Related
I was trying to log in this site using HttpClient:
https://translator.wiitrans.cn/
After trying all day, I just can not get the logged page. This is my code:
public class SimpleClient {
static String code = "";
static String captchaUrl= "https://passport.wiitrans.cn/code";
public static void logIn() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpGet httpGet = new HttpGet("https://passport.wiitrans.cn/");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("account", xxxxx));
formparams.add(new BasicNameValuePair("password", xxxxx));
formparams.add(new BasicNameValuePair("code", code));
formparams.add(new BasicNameValuePair("autologin", "1"));
UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("https://passport.wiitrans.cn/");
httppost.setEntity(entity1);
HttpResponse response = httpclient.execute(httppost);
String set_cookie = response.getFirstHeader("Set-Cookie").getValue();
System.out.println(set_cookie.substring(0, set_cookie.indexOf(";")));
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
HttpGet httpget = new HttpGet("https://translator.wiitrans.cn/");
httpget.setHeader("Cookie", set_cookie);
HttpResponse response2 = httpclient.execute(httpget);
HttpEntity entity2 = response2.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity2.getContent()));
String line = "";
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
}
public static void main(String[] args){
code = Captcha.getCaptcha(captchaUrl);
try {
logIn();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The captcha is downloaded and input manually, can anyone help me fix this?
I am trying to do an httpPost into a webservice. I want to send a list as an array. Here is what I 've done so far.
public Response searchMessages(#QueryParam("tags") List<String> tags, #QueryParam("senders") List<String> senders, #QueryParam("api_keys") List<String> apiKeys) throws Exception
{Iterator<String> tagsIt = tags.iterator();
Iterator<String> sendersIt = senders.iterator();
Iterator<String> apiKeysIt = apiKeys.iterator();
CloseableHttpClient httpClient = null;
HttpPost httpPost =null;
List<NameValuePair> nvps=null;
CloseableHttpResponse response=null;
InputStream in=null;
String myResponse = "";
try
{
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
while(tagsIt.hasNext())
{
String keyIt = tagsIt.next();
nvps.add(new BasicNameValuePair("tags",hashMap.get(keyIt)));
}
while(sendersIt.hasNext())
{
String keySend = sendersIt.next();
nvps.add(new BasicNameValuePair("senders",hashMap.get(keySend)));
}
while(apiKeysIt.hasNext())
{
String keySend = sendersIt.next();
nvps.add(new BasicNameValuePair("apiKeys",hashMap.get(keySend)));
}
//System.out.println(key+" "+hashMap.get(key));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,Consts.UTF_8));
response = httpClient.execute(httpPost);
BufferedReader buffer=null;
try{
//System.out.println(response.toString());
in= response.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(in));
String s = "";
while ((s = buffer.readLine()) != null) {
myResponse += s+"\n";
}
status= response.getStatusLine().getStatusCode();
resp = Response.status(status).entity(myResponse).build();
}
catch(Exception e)
{
e.printStackTrace();
}
}
finally
{
in.close();
response.close();
httpClient.close();
}
My issue is that I get a null pointer exception in in.close() line.
I do not know where my mistake is.Please help.
I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}
I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it?
I've tried with the methods offered by the HttpReponse class but didn't find it.
Thanks
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
You can modify your code like this:
//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//edit: there is already function for this
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
//Houston we have a problem
//we should do something with bad http status
return null;
}
EDIT: just one more thing ...
instead of requestToString(..); you can use EntityUtils.toString(..);
Have you tried this?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
Have you tried the following?
response.getStatusLine().getStatusCode()
i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json
what i want is to post this url from android to get that json data into androids view .
any help is highly appreciated
thanks
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
response variable will contain your json data.
Here is a function maybe you can use to post a string to a URL.
public String doHttpPost(final String fullUrl, final String body) {
final URL url = new URL(fullUrl);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// set the request mode as POST
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-charset", "utf-8");
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
// write the body.
request.writeBytes(body);
// flush output buffer
request.flush();
request.close();
// construct a read using input stream and charset.
final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
final BufferedReader in = new BufferedReader(isr);
String inputLine;
final StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine).append("\n");
}
in.close();
isr.close();
urlConnection.disconnect();
return stringBuilder.toString();
}
check below code: try this it may help you.
ArrayList nameValuePairs1 = new ArrayList();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
result is a json String. parse that json and display in any control. i displaied that in text view see below.
final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (Name.length() > 0 && Name != null) {
txtvenue.setText(Name);
} else {
txtvenue.setText(venue_name);
}
}
};
new Thread() {
public void run() {
try {
// put your result here
JSONObject jObject = new JSONObject(result);
JSONObject menuObject = jObject.getJSONObject("response");
JSONObject venueObject = menuObject.getJSONObject("venue");
Name = venueObject.getString("name");
String id = venueObject.getString("id");
Log.d("--------name---------", Name);
Log.d("--------id---------", id);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();