Http Response code 400 from android client - java

I Am getting the following response code from my server:
07-05 10:55:20.478 24688-24804/com.example.phuluso.aafs I/System.out: Response 400
The following is the Json data am trying to post to my WCF server :
{
"Title":"Mrs",
"Name":"Amber",
"Surname":"Rose",
"Email":"amber#gmail.com",
"AuthenticationLevel":"S",
"ContactNumber":"0820653887",
"Password":"123",
"Gender":"Female",
"FundingType":"NSFAS",
"CampusId":2,"StudentNumber":201431511
}
Here is my android code:
String jsonString = "";
try {
JSONStringer jsonStringer = new JSONStringer()
.object()
.key("Title").value("Mrs")
.key("Name").value("Amber")
.key("Surname").value("Rose")
.key("Email").value("amber#gmail.com")
.key("AuthenticationLevel").value("S")
.key("ContactNumber").value("0820653887")
.key("Password").value("123")
.key("Gender").value("Female")
.key("FundingType").value("NSFAS")
.key("CampusId").value(2)
.key("StudentNumber").value(201431511)
.endObject();
jsonString = jsonStringer.toString();
} catch (JSONException e) {
e.printStackTrace();
}
String http = "http://10.0.2.2:8750/WCF/UserRegistration.svc/registerStudentJson";
HttpURLConnection connection = null;
try {
System.out.println("Connecting to server");
URL url = new URL(http);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("charset", "UTF-8");
connection.setRequestProperty("Content-Length","352");
connection.setUseCaches(false);
connection.setConnectTimeout(50000);
connection.setReadTimeout(50000);
connection.connect();
System.out.println("Connected");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
// out.write(studjason.toString());
out.write(URLEncoder.encode(jsonString.toString(),"UTF-8"));
out.flush();
out.close();
int result = connection.getResponseCode();
System.out.println("Response" + " " + result);
// System.out.println(studjason.toString());
System.out.println(jsonString.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
And here is my wcf code:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/registerStudentJson", ResponseFormat =
WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void RegisterStudentJson(string student);
Implementation:
public void RegisterStudentJson(string student)
{
JavaScriptSerializer oJS = new JavaScriptSerializer();
Student studentObject = new Student();
studentObject = oJS.Deserialize<Student>(student);
RegisterStudent(studentObject);
}

Related

Upload an attachment to azure devops [REST API]

I'm having a hard time adding a attachments in my azure devops repo via api...
public static void putAttachments(Integer id) {
try {
URL url = new URL(
"https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png");
HttpURLConnection con = ResApiMain.apiConnectionAttachments(PAT, url);
File file = new File("C:\\Users\\marco.parra\\Pictures\\Screenshots\\new.png");
String base64Image = encodeFileToBase64Binary(file);
// String jsonInputString = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"" + "tpain"
// + "\"}]";
base64Image = "[" + base64Image + "]";
System.out.println("Base xs" + base64Image);
try (OutputStream os = con.getOutputStream()) {
byte[] input = Base64.decodeBase64(base64Image.getBytes("utf-8"));
System.out.println(new String(input));
os.write(input, 0, input.length);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
con.disconnect();
} catch (Exception ex) {
}
This is the connection method
public static HttpURLConnection apiConnectionAttachments(String PAT, URL url) {
HttpURLConnection con = null;
try {
String AuthStr = ":" + PAT;
Base64 base64 = new Base64();
String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Basic " + encodedPAT);
con.setDoOutput(true);
System.out.println("URL - " + url.toString());
System.out.println("PAT - " + encodedPAT);
// Image Requierements
// con.setRequestProperty("Content-Type", "image/jpeg");
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("X-HTTP-Method-Override", "PATCH");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/octet-stream");
// con.setRequestProperty("Accept", "application/json");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}
When i run this it show the next error code
Server returned HTTP response code: 405 for URL: https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png
Update i see how to work with python and c# but i canĀ“t follow this logic to create an attachment
https://github.com/Microsoft/azure-devops-python-api/blob/1bacd2a3f0128a6d184cf75e2c6f8859d46f270a/vsts/vsts/work_item_tracking/v4_1/work_item_tracking_client.py#L56
Expectations Example
{
"id": "a5cedde4-2dd5-4fcf-befe-fd0977dd3433",
"url": "https://dev.azure.com/fabrikam/_apis/wit/attachments/a5cedde4-2dd5-4fcf-befe-fd0977dd3433?fileName=imageAsFileAttachment.png"
}
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-5.1
Any help would be appreciated....
I solve this issue commenting line con.setRequestProperty("X-HTTP-Method-Override", "PATCH");

java.net.ConnectException Connection timed out: connect

I'm working with a RESTFul api in Java EE7. I'm using a #Stateless EJB with a method that I can reach by a HTTP Post request. I am trying to validate a recaptcha code in the server side, so I need to make a HTTP Post request to https://www.google.com/recaptcha/api/siteverify/ with my secret key and the google captcha response that the client sent.
The problem occurs when I try to make the request from the server. The exception is a ConnectException with message "Connection timed out: connect". I think I cannot connect to the web, but I am not sure. I am using NetBeans IDE 8.1
Here is the code:
#Stateless
#Path("sign-in")
public class SignIn
{
#POST
#Produces(MediaType.APPLICATION_JSON)
public javax.ws.rs.core.Response registerUser(String data) throws IOException, JSONException
{
JSONObject JObj = new JSONObject(data);
String gCaptchaResponse = JObj.getString("$captchaResponse");
if (!VerifyGCaptchaResponse(gCaptchaResponse))
{
//Response with error
}
//Logic to "sign-in"
//...
}
private final String urlverificacion = "https://www.google.com/recaptcha/api/siteverify/";
private boolean VerifyGCaptchaResponse(String GCResponse) throws JSONException
{
boolean res = false;
String paramSecret = "secret="+appSettings.getCaptchaSecretKey();
String paramResponse = "response="+GCResponse;
String urlparameters = paramSecret + "&" + paramResponse;
byte[] postData = urlparameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
HttpURLConnection connection = null;
try
{
URL url = new URL(urlverificacion);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "charset", "utf-8");
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
//Make request
OutputStream os = connection.getOutputStream(); // <<<<<<===== Here is when the problem occurs!!!
os.write(postData);
os.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Fallo conexion : codigo de error HTTP : " + connection.getResponseCode());
}
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("Respuesta del servicio .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
builder.append(output);
}
String idSicom = "0";
Integer id = 0;
JSONObject jResponse = new JSONObject(builder.toString());
if (jResponse.has("success"))
{
String success = jResponse.getString("success");
res = true;
}
else
{
}
connection.disconnect();
}
catch (java.net.ConnectException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
catch (IOException | RuntimeException | JSONException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
finally
{
}
return res;
}
}

How can i get any value from json calls (Post, Get, JSON) with Selenium WebDriver on Java?

I have a following functionality: I create through the user form a new user. After i had submitted the entered data, created user get the bar-code, which would be used for get access to the other system section by scanning that bar-code with hand-scanner. So how can i get any value (in my case that bar-code from json calls (Post, Get, JSON) with Selenium WebDriver on Java?
Selenium has nothing to do with json. You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. Given below is a simplified function for all cases.
public static HttpResponse sendRequest(String requestType, String body,String url,
String... headers) throws Exception {
try {
HttpGet getRequest = null;
HttpPost postRequest;
HttpPut putRequest;
HttpDelete delRequest;
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
// Collecting Headers
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String arg : headers) {
//Considering that you are applying header name and values in String format like this "Header1,Value1"
nvps.add(new BasicNameValuePair(arg.split(",")[0], arg
.split(",")[1]));
}
System.out.println("Total Headers Supplied " + nvps.size());
if (requestType.equalsIgnoreCase("GET")) {
getRequest = new HttpGet(url);
for (NameValuePair h : nvps) {
getRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(getRequest);
}
if (requestType.equalsIgnoreCase("POST")) {
postRequest = new HttpPost(url);
for (NameValuePair h : nvps) {
postRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
postRequest.setEntity(requestEntity);
response = client.execute(postRequest);
}
if (requestType.equalsIgnoreCase("PUT")) {
putRequest = new HttpPut(url);
for (NameValuePair h : nvps) {
putRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
putRequest.setEntity(requestEntity);
response = client.execute(putRequest);
}
if (requestType.equalsIgnoreCase("DELETE")) {
delRequest = new HttpDelete(url);
for (NameValuePair h : nvps) {
delRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(delRequest);
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Selenium only deals with browsers.
Java has classes that do http requests.
see the code below:
private HttpURLConnection setODataConnection(String url, String method) {
try {
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod(method);
// add request header
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json;odata=verbose");
return conn;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private StringBuilder sendODataRequest(HttpURLConnection conn) {
try {
int responseCode = conn.getResponseCode();
String method = conn.getRequestMethod();
System.out.println("\nSending '" + method + "' request to URL : " + conn.getURL());
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private ArrayList<String> getByFullUrl(String fullUrl, String entity) {
HttpURLConnection conn = setODataConnection(fullUrl, "GET");
StringBuilder response = sendODataRequest(conn);
ArrayList<String> s = new ArrayList<String>();
Pattern p = Pattern.compile(entity + "\" : (.*?)\\}");
Matcher m = p.matcher(response);
while (m.find()) {
s.add(m.group(1).replace("\"", ""));
}
return s;
}
public ArrayList<String> get(String table, String entity) {
String url = oDataUrl + table + "?$select=" + entity;
return getByFullUrl(url, entity);
}
public void post(String table, String bodyDetails) {
String url = oDataUrl + table;
HttpURLConnection conn = setODataConnection(url, "POST");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}
public void put(String table, String id, String bodyDetails) {
String url = oDataUrl + table + "(" + id + ")";
HttpURLConnection conn = setODataConnection(url, "PUT");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}

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.

How to stream a JSON object to a HttpURLConnection POST request

I can not see what is wrong with this code:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
On the server, I am getting no post content at all, a zero length string.
Try
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
...
osw.write(msg.toString());
osw.flush();
osw.close();
to send data.
to retrieve data try:
BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
public String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}`
call this methopd in doitbackground in asynctask
HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:
JSONObject msg; //passed in as a parameter to this method
Webb webb = Webb.create();
JSONObject result = webb.post("http://my-url/path/to/res")
.useCaches(false)
.body(msg)
.ensureSuccess()
.asJsonObject()
.getBody();
If you don't like it, there is a list of alternative libraries on the link provided.
Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!
Follow this example:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a&param2=b&param3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
this without json String post data to server
class PostLogin extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String response = null;
Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
String parm=builder.build().getEncodedQuery();
try
{
response = postData("your url here/",parm);
}catch (Exception e)
{
e.printStackTrace();
}
Log.d("test", "response string is:" + response);
return response;
}
}
private String postData(String path, String param)throws IOException {
StringBuffer response = null;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
OutputStream out = connection.getOutputStream();
out.write(param.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
}
return response.toString();
}

Categories

Resources