I cannot connect to my server using HttpClient when Posting, it works fine with get, and works fine with post to other servers (such as google), any ideas?
I am NOT using android.
The server responds fine when accessing it by browser.
As it is probably a server config issue, i do not have full access to the server, it is a hosted webserver, however i have access to the cpanel
private static String GetURL(String inUrl, String post) {
String inputLine = "";
try {
if (!inUrl.contains("http")) {
throw new Exception("Invalid URL");
} else {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(inUrl);
httpPost.addHeader("Accept-Charset", "UTF-8");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//create post
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("req", post));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
inputLine = in.readLine();
in.close();
}
}catch (Exception ex) {
inputLine = "" + Comms.ERROR_COULD_NOT_REACH_SERVER;
Log.writeLog("Could Not Reach Server: \"" + inUrl + "\"");
ex.printStackTrace();
}
return inputLine;
}
org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at Comms.GetURL(Comms.java:87)
at Comms.sendCommand(Comms.java:64)
at Comms.main(Comms.java:43)
Related
I am trying to upload an image for whataspp cloud api , i've transformed curl code to c# using RestSharp but i got this error . I was triying to change the file parameter format but it doesn't work. I don't know if i am missing something in the json maybe.
here is the code i use :
public void whatsapp_image_upload()
{
var client = new RestClient("https://graph.facebook.com/" + num_whatsapp_business + "/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + token_authorization);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("messaging_product", "whatsapp");
request.AddParameter("file", "C:\\Users\\cnarea\\Pictures\\empaque.jpg");
request.AddParameter("type", "image/jpeg");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
and this is the error i recieve :
{"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AFWXnEVRuvp82ewjaUEtoLa"}}
Well i was able to solve it, i have to use postman app to obtain c# code ,my code is this :
public void whatsapp_image_upload()
{
try
{
string filePath = #"C:\Users\cnarea\Pictures\procesos.jpeg";
var client = new RestClient("https://graph.facebook.com/"+num_whatsapp_business+"/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer "+token_authorization);
request.AddFile("file", filePath, "image/jpeg");
request.AddParameter("messaging_product", "whatsapp");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I am trying to create new document in Docushare Flex using new docushare rest api and my request body suppose to be XML and I am generating it with requested data, when I send the request I get this error "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml(filePath, parentId, documentTitle, fileName, ownerId);
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
StringEntity bodyEntity = new StringEntity(createDocumentXml, ContentType.MULTIPART_FORM_DATA);
request.setEntity(bodyEntity);
CloseableHttpResponse response = client.execute(request);
System.out.println("Status is " + response.getStatusLine());
HttpEntity entity = response.getEntity();
I have used this block of code to upload a document in DocuShare Flex
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml();
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
FileBody body = new FileBody(file.toFile());
StringBody xmlContent = new StringBody(createDocumentXml, ContentType.APPLICATION_XML);
String boundry = UUID.nameUUIDFromBytes(file.toString().getBytes()).toString();
HttpEntity entity = MultipartEntityBuilder.create()
.setBoundary(boundry)
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)`enter code here`
.addPart("content", body)
.addPart("request", xmlContent)
.build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
i am using sinch from java, i recently reput credit to the account, and now when i try to send message i get succes message, but the sms isn't send. Following the link https://messagingapi.sinch.com/v1/sms/162393899 i get this
{"errorCode":40107,"message":"Invalid authorization key:
vivi******#gmail.com","reference":"BA:vivi******#gmail.com_GtIfKPDMJEKL4VJWR0kkJQ"}
the code
try {
String phoneNumber = "+40732******";
String appKey = "*****";
String appSecret = "****";
String message = "Test";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
I (want to) use CommunityService.updateCommunityLogo(file, communityUuid) to set a logo for a freshly programmatically created community.
The call runs though without error, but the logo is not changed.
When I look into the apache.http.wire logs, it shows following conversation:
>> PUT /communities/service/html/image?communityUuid=6e700c5d-082c-497f-8657-d516a01f62e7 HTTP/1.1 (without data so far)
<< HTTP/1.1 100 Continue
>> (binary data of image)
apache.http.wire(78): << "HTTP/1.1 100 Continue[EOL]"
apache.http.wire(78): << "[EOL]"
impl.conn.DefaultClientConnection(229): Receiving response: HTTP/1.1 100 Continue
apache.http.headers(232): << HTTP/1.1 100 Continue
apache.http.wire(78): << "HTTP/1.1 200 OK[EOL]"
impl.conn.DefaultClientConnection(229): Receiving response: HTTP/1.1 200 OK
apache.http.headers(232): << HTTP/1.1 200 OK
apache.http.wire(64): << "<script language="JavaScript1.2">[\n]"
apache.http.wire(64): << " document.cookie = "CommunitiesReqURL=" + location.href + "; expires=" +[\n]"
apache.http.wire(64): << " new Date(new Date().getTime() + 365*24*60*60*1000).toGMTString() + "; path=/communities";[\n]"
apache.http.wire(64): << " location.href = "/communities/service/html/login";[\n]"
apache.http.wire(64): << "</script>[\n]"
I have skipped some details like Date, Content fields etc. from header and wire, but this is what basically happens.
This in turn is part of a request processing from inside a web application which should automatically do some things on a Connections instance. Thus, as a result, this web application will present the answer to the original user request to the user as a web page. This in turn contains a frame with the community which was changed here -- but after this step the user is forced to login anew on Connections (although the LTPA token is "fresh") in full-window mode.
Thus I suspect that calling CommunityService.updateCommunityLogo(file, communityUuid) forces re-authentication and destroys/invalidates the current LTPA token or authenticated session.
What is happening here?
What can I do about it?
Remarks:
I have no access to any Connections logs actually.
The Connections instance is v4.5 and directly accessed using BasicAuth in IBM SBT, but uses form-based auth in the browser.
The SBT version is 1.0.2.20140527-1807, included using maven 3.0.5, deployed on tomcat 7.0.53 on Java 7.
it's actually most likely related to the 100 continue for that API
I wrote an article on it http://bastide.org/2014/06/19/expect-100/
For J2EE Apps, navigate to your managed-beans.xml. Locate the Endpoint you want to disable it for, add a managed-property.
forceDisableExpectedContinue
true
some sample code I wrote for this...
public static void main(String[] args){
URL url;
try {
String imageUrl = "https://servername.com/communities/service/html/image?communityUuid=1e244250-6740-4949-aaac-682707a47099";
String imageType = "image/png";
String folder = "/Users/paulbastide/Desktop/";
String fileName = "demo.png";
File file = new File(folder + fileName);
long fileLength = 0l;
String userAgent = "Apache-HttpClient/4.3.3 (java 1.5)";
String auth = "Basic =";
url = new URL(imageUrl);
HttpsURLConnection httpCon = (HttpsURLConnection) url.openConnection();
httpCon.setDoOutput(true);
//https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance( "SSL" );
sslContext.init( null, trustAllCerts, new java.security.SecureRandom() );
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
httpCon.setSSLSocketFactory( sslSocketFactory );
/**
* adds the cookies
*/
httpCon.setRequestProperty("Cookie", "");
// Responds to two operations PUT and DELETE
httpCon.setRequestMethod("PUT");
httpCon.setRequestProperty("Content-Type", imageType );
httpCon.setRequestProperty("slug", fileName);
httpCon.setRequestProperty("Content-Length", "" + fileLength );
httpCon.setRequestProperty("Content-Encoding", "binary");
httpCon.setRequestProperty("User-Agent", userAgent);
httpCon.setRequestProperty("Authorization", auth);
byte[] fileBytes = FileUtils.readFileToByteArray( file);
DataOutputStream out = new DataOutputStream(
httpCon.getOutputStream());
out.write(fileBytes);
out.close();
httpCon.getInputStream();
System.out.println("The Response Code is " + httpCon.getResponseCode());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
IBM SBT SDK 1.0.3 solves this problem: Tests with the same application code and 1.0.2 / 1.0.3 revealed that 1.0.2 is buggy here, but in 1.0.3 this issue is fixed.
Additionally however the server side has undergone an upgrade from IC 4.5 to IC 5.0, but with the 1.0.2 IBM SBT SDK also IC5 did not accept the logo. Thus it might be both: IC45 -> IC5 AND SBT 1.0.2 -> 1.0.3.
I'm creating an Android app that should do the following;
Use a form on a https (SSL!) page to login and receive a cookie
Issue httpGET actions to get html
parse that html and show it in a view, list or something.
I've been fooling around with Jsoup, httpUnit and HTMLUnit for quite some time now, but I'm running in to several problems;
A. Login is fine, works.. (I get the website's welcome page) but then, when I issue a GET statement (and include the cookie), I am redirected to the login form. So the response html is not what I expected. (might have something to do with a keepalivestrategy?)
B. InputBuffers are too small to receive entire HTML pages and set them up for parsing.
NB : I do not have control over the webserver
I'm totally new at this, so a tutorial or code snippets would be helpful.
For instance, this is what I use to login to the website :
public int checkLogin() throws Exception {
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("userid", getUsername()));
data.add(new BasicNameValuePair("password", getPassword()));
data.add(new BasicNameValuePair("submit_login", "Logmein"));
Log.d(TAG, "Cookie name : " + getCookieName());
Log.d(TAG, "Cookie cont : " + getCookie());
HttpPost request = new HttpPost(BASE_URL);
request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.getParams().setParameter("http.protocol.handle-redirects",false);
request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
HttpResponse response;
httpsclient.getCookieStore().clear();
List<Cookie> cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies pre-login : " + cookies.size());
response = httpsclient.execute(request);
cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies post-login : " + cookies.size());
String html = "";
// Problem : buffer is too small!
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
Document doc = Jsoup.parse(html);
Log.v(TAG, "Ik heb nu dit : " + doc.toString());
if (cookies.size() > 0){
storeCookie(cookies.get(0).getName(), cookies.get(0).getValue());
return MensaMobileActivity.REQUEST_SUCCESS;
} else {
return MensaMobileActivity.REQUEST_ERROR;
}
}
You don't handle the SSL certificate at all, that's at least a part of the problem. I struggled starting to learn this recently as well. This block of code will grab the SSL cert from the webpage you're accessing.
try {
URL url = new URL(YOUR_WEBPAGE_HERE);
HttpsURLConnection connect = (HttpsURLConnection)url.openConnection();
connect.connect();
Certificate[] certs = connect.getServerCertificates();
if (certs.length > 0) {
cert = new File("YOUR_PATH_TO_THE_FILE");
//write the certificate obtained to the cert file.
OutputStream os = new FileOutputStream(cert);
os.write(certs[0].getEncoded());
return true;
}
}
catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (CertificateEncodingException e) {
e.printStackTrace();
}