Socket TimeOutException-Connection timed out - java

I am trying to connect with Tomcat Server(IP address-192.168.1.120 which is stored in Config.java(static variable APP_SERVER_URL)) but it is giving me socket timeout exception .
How to resolve it.Please help.
But when I
public class ShareExternalServer {
public String shareRegIdWithAppServer(Map<String, String> paramsMap) {
String result = "";
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry<String, String>> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
Log.d("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&",body);
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httpCon.setConnectTimeout(20000);
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
Log.d("$$$$$$$$$$$$$$$$$$",String.valueOf(status));
/* if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status+regId;
}*/
} finally {
if (httpCon != null) {
((HttpURLConnection) httpCon).disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}

Related

(GET http request) How send cookie in the server

I'm trying to send cookies to the server, but it doesn't work. Please tell me thats wrong. Here is my code.
At first, I take cookie in the POST request.
> Map <String, List<String>> headerFields = postRequest.getHeaderFields();
> List<String> cookiesHeader = headerFields.get("Set-Cookie");
Later, in the GET request, i'm send cookie to the server.
getRequest.setRequestProperty("Cookie", cookiesHeader.toString());
Help me. I'm beginner, not judge strictly.
Here all my code.
#Override
protected String doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
String store_id = "";
final String COOKIES_HEADER = "Set-Cookie";
final String COOKIE = "Cookie";
try {
Thread.sleep(4000);
Log.i(TAG, "httpRequest start");
String parametrs = mPhone.getText().toString();
String parametrs2 = mPass.getText().toString();
JSONObject allParams = new JSONObject();
HttpURLConnection postRequest = null;
InputStream inputStream = null;
byte[] data = null;
try {
URL serverUrl = new URL("https://api.fianitlombard.ru/mobile/auth");
postRequest = (HttpURLConnection) serverUrl.openConnection();
postRequest.setReadTimeout(10000 /* milliseconds */);
postRequest.setConnectTimeout(15000 /* milliseconds */);
postRequest.setRequestMethod("POST");
postRequest.setDoInput(true);
postRequest.setDoOutput(true);
postRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
postRequest.connect();
allParams.put("phone", parametrs);
allParams.put("password", parametrs2);
Log.i(TAG, "allParams" + allParams);
OutputStream bos = (postRequest.getOutputStream());
bos.write(allParams.toString().getBytes());
String helpInfo = postRequest.getResponseMessage();
Log.i(TAG, "helpInfo =" + helpInfo);
responseCode = postRequest.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Map<String, List<String>> headerFields = postRequest.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (responseCode == 200) {
inputStream = postRequest.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
Log.i(TAG, "responseCode = " + responseCode);
Log.i(TAG, "resultCode = " + resultString);
JSONObject jsonObject = new JSONObject(resultString);
store_id = jsonObject.getString("store_id");
Log.i(TAG, "store_id =" + store_id);
bos.close();
baos.close();
postRequest.disconnect();
}
if (responseCode == 403) {
Log.i(TAG, "responseCode = " + responseCode);
}
HttpURLConnection getRequest = null;
try {
URL serverUrl1 = new URL("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
URI uri = URI.create("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
getRequest = (HttpURLConnection) serverUrl1.openConnection();
getRequest.setReadTimeout(20000 /* milliseconds */);
getRequest.setConnectTimeout(25000 /* milliseconds */);
getRequest.setRequestMethod("GET");
getRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
Log.i(TAG, "Cookie = " + cookiesHeader.toString());
getRequest.connect();
int responceGetCode = getRequest.getResponseCode();
String responceGetInfo = getRequest.getResponseMessage();
Log.i(TAG, "responceGetCode = " + responceGetCode);
Log.i(TAG, "responceGetInfo = " + responceGetInfo);
if (responceGetCode == 200) {
//Все хорошо
}
if (responceGetCode == 400) {
// Устарела версия, нужно обновление
}
if (responceGetCode == 403) {
//Проблемы с авторизацией
} else {
//Что то другое.
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (getRequest != null)
getRequest.disconnect();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if (postRequest != null) {
postRequest.disconnect();
}
Log.i(TAG, "httpRequest end");
}
catch (InterruptedException | JSONException e) {
e.printStackTrace();
}
return store_id;
}
change below line
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
to
getRequest.setRequestProperty( COOKIE, cookiesHeader.get( 0 ) );
toString() method of List will return the hashCode() but not the actual values of List
try to use the following method to get the cookie :
String getHeaderField("Set-Cookie")
you set the cookie by using the lists toString method, which will not give you the current cookie representation, but instead a string matching "[var1, var2, var3]"
The server sends the following in its response header to set a cookie field.
Set-Cookie:name=value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:name=value
See the HTTP Cookie article at Wikipedia for more information.

Android - Send XML file to PHP API server using HttpURLConnection

So currently, I'm trying to import some data in the form of an XML file to a server. I have successfully logged in and am doing everything through the API of the server. The website/server responds in XML, not sure if that is relevant.
When I use the import data action of the API, the request method is actually a GET and not a POST and the response content-type is text/xml. I want to strictly stick to using HttpURLConnection and I understand that sending this XML file will require some multipart content-type thing but I'm not really sure how to proceed from here.
I've looked at these two examples but it does not work for my application (at least not directly). In addition, I don't really understand where they got some of the request headers from.
Send .txt file, document file to the server in android
http://alt236.blogspot.ca/2012/03/java-multipart-upload-code-android.html
A message from one of the developers have said "To upload the data use the action=importData&gwID=nnnn and with the usual
Multipart content encoding and place the files in the request body as usual."
How would I send my XML file to my server through its API?
This is how you do it:
public void postToUrl(String payload, String address, String subAddress) throws Exception
{
try
{
URL url = new URL(address);
URLConnection uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) uc;
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "text/xml");
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(payload);
pw.close();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
bis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is my implementation of a Multipart form data upload using HttpURLConnection.
public class WebConnector {
String boundary = "-------------" + System.currentTimeMillis();
private static final String LINE_FEED = "\r\n";
private static final String TWO_HYPHENS = "--";
private StringBuilder url;
private String protocol;
private HashMap<String, String> params;
private JSONObject postData;
private List<String> fileList;
private int count = 0;
private DataOutputStream dos;
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
createServiceUrl();
}
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData, List<String> fileList) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
this.fileList = fileList;
createServiceUrl();
}
public String connectToMULTIPART_POST_service(String postName) {
System.out.println(">>>>>>>>>url : " + url);
StringBuilder stringBuilder = new StringBuilder();
String strResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(1024);
urlConnection.setRequestMethod("POST");
dos = new DataOutputStream(urlConnection.getOutputStream());
Iterator<String> keys = postData.keys();
while (keys.hasNext()) {
try {
String id = String.valueOf(keys.next());
addFormField(id, "" + postData.get(id));
System.out.println(id + " : " + postData.get(id));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
for (int i = 0; i < fileList.size(); i++) {
File file = new File(fileList.get(i));
if (file != null) ;
addFilePart("photos[" + i + "][image]", file);
}
}
// forming th java.net.URL object
build();
urlConnection.connect();
int statusCode = 0;
try {
urlConnection.connect();
statusCode = urlConnection.getResponseCode();
} catch (EOFException e1) {
if (count < 5) {
urlConnection.disconnect();
count++;
String temp = connectToMULTIPART_POST_service(postName);
if (temp != null && !temp.equals("")) {
return temp;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 200 represents HTTP OK
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
} else {
System.out.println(urlConnection.getResponseMessage());
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
}
}
return strResponse;
}
public void addFormField(String fieldName, String value) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
/*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
dos.writeBytes(value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addFilePart(String fieldName, File uploadFile) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
dos.writeBytes(LINE_FEED);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dos.writeBytes(LINE_FEED);
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
/* close streams */
fStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHeaderField(String name, String value) {
try {
dos.writeBytes(name + ": " + value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
/* Close Stream */
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private void createServiceUrl() {
if (null == params) {
return;
}
final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
boolean isParam = false;
while (it.hasNext()) {
final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
url.append(mapEnt.getKey());
url.append("=");
try {
url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
url.append(WSConstants.AMPERSAND);
isParam = true;
}
if (isParam) {
url.deleteCharAt(url.length() - 1);
}
}
}

HttpUrlConnection Forbidden access to Google Shortener URL

I have implemented a class to get a short url from a long url:
public class URLShortener {
private final static String TAG = "URLShortener";
private final static String ADDRESS = "https://www.googleapis.com/urlshortener/v1/url?key=API_KEY";
static JSONObject jObj = null;
static String json = "";
private String longUrl;
public URLShortener(String longUrl) {
this.longUrl = longUrl;
}
//public JSONObject getJSONFromUrl(String address,String longUrl) {
public JSONObject getJSONFromUrl() {
URL url;
HttpURLConnection urlConnection = null;
// Making HTTP request
try {
//Define connection
url = new URL(URLShortener.ADDRESS);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
//Define JSONObject
JSONObject dataSend = new JSONObject();
Log.d(TAG, "longURL: " + URLEncoder.encode(this.longUrl, "UTF-8"));
dataSend.put("longURL", URLEncoder.encode(this.longUrl, "UTF-8"));
//Send data
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(dataSend.toString());
wr.flush();
wr.close();
Log.d(TAG, "Data send");
Log.d(TAG, "ResponseCode: " + String.valueOf(urlConnection.getResponseCode()));
//Display what returns POST request
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
//System.out.println(""+sb.toString());
Log.d(TAG, "sb: " + sb.toString());
}else{
//System.out.println(urlConnection.getResponseMessage());
Log.d(TAG, "urlConnection.getResponseMessage(): " + urlConnection.getResponseMessage());
}
json = sb.toString();
Log.e("JSON", json);
// Parse the String to a JSON Object
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d(TAG, "UnsuppoertedEncodingException: " + e.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "Error JSONException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "IOException: " + e.toString());
}
// Return JSON Object
return jObj;
}
}
When I call the method getJSONFromUrl I've got always the same result ResponseCode = 403 (Forbidden).
What am I doing wrong?

Search Tweets with pure Java 400 get Bad Request

I tried use search tweets use twitter search api.
But when i get bearer token then send request to
/1.1/search/tweets.json?count=2
Its response is 400 (Bad Request)
I don't know how is wrong... Anyone can help me ??
Here is my Code all from http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
I also watch Application-only authentication but still don't know why.
Hope someone can tell me ....
private final static String getTokenURL = "https://api.twitter.com/oauth2/token";
private static String bearerToken;
static final String ACCESS_TOKEN = "1111111112-H************************************s";
static final String ACCESS_SECRET = "S************************************n";
static final String CONSUMER_KEY = "q************************************g";
static final String CONSUMER_SECRET = "Q************************************a";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
bearerToken = requestBearerToken(getTokenURL);
searchTweets("https://api.twitter.com/1.1/search/tweets.json?count=2");
} catch (IOException e) {
System.out.println("IOException e");
e.printStackTrace();
}
}
}).start();
}
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
} catch (UnsupportedEncodingException e) {
return new String();
}
}
private static String requestBearerToken(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys(CONSUMER_KEY, CONSUMER_SECRET);
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
System.out.println(connection);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Basic "
+ encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());
String result = readResponse(connection);
JSONObject jsonResult=new JSONObject(result);
if (jsonResult.get("token_type") != null && jsonResult.get("token_type").equals("bearer") ) {
return jsonResult.getString("access_token");
}
return new String();
} catch (MalformedURLException | JSONException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static String searchTweets(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Bearer " + bearerToken);
connection.setUseCaches(false);
String result = readResponse(connection);
System.out.println("fetchTimelineTweet---result:"+result);
if (result != null || result.equals("")) {
return result;
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpURLConnection connection,
String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
} catch (IOException e) {
return false;
}
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
} catch (IOException e) {
return new String();
}
}
You're missing a query variable q, which is a required parameter.
Try changing your request url to: https://api.twitter.com/1.1/search/tweets.json?count=2&q=test

Internal server Error 500 when I try to automate login to facebook in java

I am largely following this :
http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/
I am able to get the form details. I even constructed the params. Then when I post the request, I get internal server error 500!
Whats wrong ? here is my code :
public class Abc {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) {
String proxyHost="43.88.65.10";
String proxyPort="8080";
System.out.println("Setting proxy....");
System.setProperty("http.proxyHost",proxyHost) ;
System.setProperty("https.proxyHost",proxyHost) ;
System.setProperty("https.proxyPort",proxyPort) ;
System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1|43.88.102.142");
System.setProperty("https.nonProxyHosts", "localhost|127.0.0.1|43.88.102.142");
System.out.println("Proxy Set.");
String url = "https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXX&redirect_uri=http://localhost:9091&scope=read_stream";
String fb = "https://www.facebook.com/login.php?login_attempt=1&next=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Foauth%3F&redirect_uri=http://localhost:9091/test&scope=publish_stream&client_id=XXXXXXXXXXXX&ret=login";
Abc tryObject = new Abc();
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = null;
try {
page = tryObject.GetPageContent(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String postParams = null;
try {
postParams = tryObject.getFormParams(page, "xxxxxxx#gmail.com", "xxxxx");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("postParams"+postParams);
//postParams = "lsd=AVoao3Js&api_key=XXXXXXXXXXXXX&display=page&enable_profile_selector=&legacy_return=1&profile_selector_ids=&skip_api_login=1&signed_next=1&trynum=1&timezone=&lgnrnd=044127_BBYN&lgnjs=n&email=XXXXXXXXXXX%40gmail.com&pass=XXXXXXXX&persistent=1&default_persistent=0&login=Log+In";
// 2. Construct above post's content and then send a POST request for
// authentication
//tryObject.sendPost(url, postParams);
try {
tryObject.sendPost(fb, postParams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of main
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
System.out.println("doc-->"+doc);
//FB form id
Element loginform = doc.getElementById("loginform");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equalsIgnoreCase("Email"))
value = username;
else if (key.equalsIgnoreCase("Pass"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.facebook.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://www.facebook.com/");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
System.out.println("Length-->"+postParams.length());
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
The error I get is
Response Code : 500
java.io.IOException: Server returned HTTP response code: 500 for URL: https://www.facebook.com/login.php?login_attempt=1&next=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Foauth%3F&redirect_uri=http://localhost:9091/test&scope=publish_stream&client_id=XXXXXXXXXX&ret=login
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at facebook.Abc.sendPost(Abc.java:216)
at facebook.Abc.main(Abc.java:78)
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://www.facebook.com/login.php?login_attempt=1&next=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Foauth%3F&redirect_uri=http://localhost:9091/test&scope=publish_stream&client_id=XXXXXXXXX&ret=login
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at facebook.Abc.sendPost(Abc.java:210)
... 1 more
I am posting most of the code below so that it can help others(a big thanku to MKYONG :) )
public class FbLogin {
private List<String> cookies;
private HttpURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
private final String PROXY_HOST = "XXXXXXX";
private final String PROXY_PORT = "80";
private final String charset = "UTF-8";
private final String REDIRECT_URI = "http://localhost:8000/";
boolean redirect = false;
private void setProxy(){
System.setProperty("http.proxyHost", PROXY_HOST);
System.setProperty("http.proxyPort", PROXY_PORT);
System.setProperty("https.proxyHost", PROXY_HOST);
System.setProperty("https.proxyPort", PROXY_PORT);
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public static void main(String[] args) {
String USERNAME = "XXXXX#gmail.com";
String PASSWORD = "XXXXXX";
FbLogin httpd = new FbLogin();
httpd.setProxy();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
String page = "";
try {
page = httpd.sendGet();
} catch (Exception e) {
e.printStackTrace();
}
String postParams = "";
try {
postParams = httpd.getFormsParams(page, USERNAME, PASSWORD);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpd.sendPost(postParams);
} catch (Exception e) {
e.printStackTrace();
}
}
private String sendGet() {
//Generating map for url path and query
String loginUrl = "http://www.facebook.com/v1.0/dialog/oauth";
LinkedHashMap<String, String> queryMap = new LinkedHashMap<String, String>();
queryMap.put("redirect_uri", REDIRECT_URI);
queryMap.put("scope", "read_stream");
queryMap.put("client_id", "XXXXXXXXX");
queryMap.put("ret", "login");
//Creating URL with urlencoder
String fbUrlString = generateUrl(loginUrl, queryMap);
System.out.println("Generated Url ---> " + fbUrlString);
URL myFbURL = null;
try {
myFbURL = new URL(fbUrlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myFbURL.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
//optional -default is GET
try {
conn.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
//add request headers
conn.addRequestProperty("User-Agent", "Mozilla");
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//Normally 3xx response code is for redirect
int responseCode = 0;
try {
responseCode = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println( "Sending GET request to URL " + myFbURL);
System.out.println( "Resonse code = " + responseCode);
checkForRedirect(responseCode);
return readPage();
}
private void sendPost(String postParams) throws Exception {
String Url = "https://www.facebook.com/login.php";
LinkedHashMap<String, String> queryMap = new LinkedHashMap<String, String>();
queryMap.put("login_attempt", "1");
queryMap.put("next", "https://www.facebook.com/v1.0/dialog/oauth?redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&scope=read_stream&client_id=XXXXXXXX&ret=login");
//Creating URL with urlencoder
String postUrl = generateUrl(Url, queryMap);
System.out.println( "Generated Url ---> " + postUrl);
URL obj = new URL(postUrl);
conn = (HttpURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// for (String cookie : this.cookies) {
// conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
// }
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + postUrl);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
checkForRedirect(responseCode);
readPage();
}
private String getFormsParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println( "Extracting forms data");
Document doc = Jsoup.parse(html);
//Facebook form
Element loginForm = doc.getElementById("login_form");
Elements inputElements = loginForm.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for(Element inputElement : inputElements ) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
System.out.println("key --> " + key);
System.out.println("value --> " + value);
if (key.equalsIgnoreCase("email")){
value = username;
}
else if(key.equalsIgnoreCase("pass")){
value = password;
}
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
//build parameter list
StringBuilder result = new StringBuilder();
for(String param : paramList) {
if(result.length() == 0){
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
private String readPage(){
BufferedReader buffReader = null;
try {
buffReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
StringBuffer response = new StringBuffer();
try {
while ((inputLine = buffReader.readLine()) != null) {
response.append(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
private void redirectHandler(){
//If redirect is true launch the new redirected url
if(redirect) {
// get redirect url from "location" header field
String newURL = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
try {
conn = (HttpURLConnection) new URL(newURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// conn.setRequestProperty("Cookie", cookies)
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
System.out.println( "Redirecting to " + conn.getURL());
try {
System.out.println( "Resonse code = " + conn.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
try {
checkForRedirect(conn.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void checkForRedirect(int responseCode){
if(responseCode != HttpURLConnection.HTTP_OK) {
if(responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
redirect = true;
redirectHandler();
}
}
}
private String generateUrl(String url, LinkedHashMap<String, String> queryMap) {
System.out.println( "Inside generateUrl method ...");
StringBuilder query = new StringBuilder();
char separator = '?';
for(Entry<String, String> entry : queryMap.entrySet()) {
query.append(separator);
separator = '&' ;
try {
query.append(URLEncoder.encode(entry.getKey(), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
query.append("=");
try {
query.append(URLEncoder.encode(entry.getValue(), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
url = url + query;
return url;
}
}
"Internal Server Error 500" means your code made the server crash. There is some bug in your code.

Categories

Resources