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?
Related
So when i use postman(google app) to send a post method to my php file on my web server, i got a full respond back with all the correct information. but when i am trying to do the same thing on android, i am getting [] in response everytime.
#Override
protected Profile doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://www.secretvoice1.com/getData.php");
Profile returnUser = null;
try {
HttpResponse httpResponse = client.execute(post);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
HttpEntity entity = httpResponse.getEntity();
Log.d("11111:", httpResponse.toString());
String result = EntityUtils.toString(entity);
System.out.println(result);
Log.d("222222", result);
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() == 0) {
returnUser = null;
Log.d("this:", "here");
} else {
//String name = jsonObject.getJSONArray("name");
//String password = jsonObject.getString("password");
//String email = jsonObject.getString("email");
returnUser = new Profile(user.name, user.password, user.email);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
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.
NODE.js : (zip the file)
app.post('/api/db', function(req, res){
if(req.body.type == 'Control'){
var zip = new AdmZip();
console.log(req.body.type);
zip.addLocalFolder(__dirname +'/XXX/Temp/1');
var willSendthis = zip.toBuffer();
zip.writeZip(__dirname +'/files.zip');
res.sendFile(zip);
}
});
JAVA : (send a request to want to zip file)
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
public ArrayList<String> aList= new ArrayList<String>();
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "Control"));
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String result) {
}
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "PUT"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
url = url.trim();
Log.d("url = ", URLEncoder.encode(url, "UTF-8"));
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-9"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I sent .zip file from server to android devices. I want to save into the android devices memory.
How can i save .zip file which is sended by node.js server?
I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, String taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}
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(); }
}