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");
Related
I am working one web application spring MVC.i want to send sms using web.
I tried below code.
If i run single java file using main() then its working and when i tried it through web its not working.
Can anybody help me to solve this.
Below is my code
public static String doSendSMS(String url_str) {
StringBuffer response = new StringBuffer();
try {
URL obj = new URL(url_str);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url_str);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
}
return response.toString();
}
Below is working code.
public class sms {
private static String sessionCookie;
public static String loginSMS(String userName, String password,String url) {
String cookie = null;
URL urlLogin;
String loginContent;
HttpURLConnection loginConnection;
try {
//UTF-8 encoding is the web standard so data must be encoded to UTF-8
userName = URLEncoder.encode(userName, "UTF-8");
password = URLEncoder.encode(password, "UTF-8");
urlLogin = new URL(url);
loginConnection = (HttpURLConnection) urlLogin.openConnection();
loginContent = "username=" + userName + "&password=" + password;
loginConnection.setDoOutput(true);
loginConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
loginConnection.setRequestProperty("Content-Length", String.valueOf(loginContent.length()));
loginConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
loginConnection.setRequestProperty("Accept", "*/*");
loginConnection.setRequestProperty("Referer", url);
loginConnection.setRequestMethod("POST");
loginConnection.setInstanceFollowRedirects(false);
//Writing the Content to the site
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(loginConnection.getOutputStream()), true);
printWriter.print(loginContent);
printWriter.flush();
printWriter.close();
//Reading the cookie
cookie = loginConnection.getHeaderField("Set-Cookie");
} catch (MalformedURLException ex) {
System.err.println("Login URL Error");
} catch (UnsupportedEncodingException ex) {
System.err.println("Error in encoding Username or Password");
} catch (IOException ex) {
System.err.println("Can not connect to Login URL");
}
if (cookie == null || cookie.isEmpty()) {
System.err.println("Some error occured...Try again in a few seconds..If still problem exists check your username and password");
}
sessionCookie = cookie;
return cookie;
}
public static void sendSMS( String action,String urlString,String content) {
loginSMS("user", "user123","url");
URL sendURL;
HttpURLConnection sendConnection;
String sendContent;
try {
sendURL = new URL(urlString);
sendConnection = (HttpURLConnection) sendURL.openConnection();
// sendContent="custid=undefined&HiddenAction=instantsms&Action="+action+"&login=&pass=&MobNo="+ phoneNumber+ "&textArea="+message;
sendContent = content;
sendConnection.setDoOutput(true);
sendConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
sendConnection.setRequestProperty("Content-Length", String.valueOf(sendContent.getBytes().length));
sendConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
sendConnection.setRequestProperty("Accept", "*/*");
sendConnection.setRequestProperty("Cookie", sessionCookie);
sendConnection.setRequestMethod("POST");
sendConnection.setInstanceFollowRedirects(false);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(sendConnection.getOutputStream()), true);
printWriter.print(sendContent);
printWriter.flush();
printWriter.close();
//Reading the returned web page to analyse whether the operation was sucessfull
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sendConnection.getInputStream()));
StringBuilder SendResult = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
SendResult.append(line);
SendResult.append('\n');
//Message has been submitted successfully
}
System.out.println("Responce : " + SendResult);
bufferedReader.close();
logoutSMS();
} catch (UnsupportedEncodingException ex) {
System.err.println("Message content encoding error");
// System.exit(0);
} catch (MalformedURLException ex) {
System.err.println("Sending URL Error");
// System.exit(0);
} catch (IOException ex) {
System.err.println("Sending URL Connection Error");
ex.printStackTrace();
// System.exit(0);
}
}
}
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);
}
I am getting an error that I am unauthorized.. RESPONSE CODE 401
The token I am using works in perl..
This is what I have tried till now:
public static void main(String[] args) throws Exception {
try {
String auth = returnAuth(); //getting token from a file.
//System.out.println(auth);
String url1= "https://canvas.instructure.com/api/v1";
URL url = new URL(url1+"/courses");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setRequestProperty("Authorization", "Bearer " + auth);
connection.setRequestProperty("Authorization", "Bearer "+auth);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
try {
String auth = returnAuth(); //getting token from a file.
String url1= "https://canvas.instructure.com/api/v1/courses";
URL url = new URL(url1);
HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer "+auth);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
You have it commented out but every Oauth server I've dealt with would be "Bearer <token>" - one space and no colon.
You set the parameters AFTER you called!
Change your code to first set the authentication, then open the connection.
String url1= "https://canvas.instructure.com/api/v1";
URL url = new URL(url1+"/courses");
connection.setRequestProperty("Authorization", "Bearer "+auth);
connection.setRequestMethod("GET");
//now you can open the connection...
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Can anyone spot why this takes ~20 sec?
I am running the code below to post a JSON request to a local server 192.168.1.127.
curl -H "Content-type: application/json" -X POST
http:// 192.168.1.127:8080/bed -d
'{"command":{"value":3.012,"set":"target_pressure_voltage"},"id":2002,"side":"left","role":"command"}'
curl on the same box where the server is running is instant and the server does not complain.
A get request from the Android browser is fast. I have tried two Android devices with os version 4.x.
This question does not help as far as I can tell:
Android HttpURLConnection VERY slow
con.getInputStream() Takes ~20 sec:
String httpJson(String url, JSONObject job) {
String ret = null;
HttpURLConnection con = httpJsonCon(url);
if(con!=null)
httpJsonCon(con, url,job);
return ret;
}
HttpURLConnection mkCon(String url) {
HttpURLConnection con = null;
URL u = null;
try {
u = new URL(url);
con = (HttpURLConnection) (u.openConnection());
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "text/plain");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
} catch (Exception e) {
Log.w(TAG, " e= " + e);
if(con!=null)
con.disconnect();
con = null;
}
return con;
}
String sendJson(HttpURLConnection con, JSONObject job) {
String ret = null;
if(con==null){
return ret;
}
try {
final String toWriteOut = job.toString();
final Writer out = new OutputStreamWriter(new BufferedOutputStream(
con.getOutputStream()), "UTF-8");
out.write(toWriteOut);
out.flush();
//con.getInputStream() Takes ~20 sec:
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
} catch (IOException e) {
Log.d(TAG, " e= " + e);
ret = null;
} finally {
if(con!=null)
con.disconnect();
}
return ret;
}
Add a request header that specifies the post content length.
con.setRequestProperty("Content-Length", "" + json.length());
I'm trying to make a GET AJAX request on some site using java.
My code is the following:
String cookie = getRandomString(16); //Getting a random 32-symbol string
String url = "https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
InputStream is = conn.getInputStream();
int buffer;
while((buffer = is.read()) != -1)
System.out.print(buffer);
is.close();
conn.disconnect();
But the problem is that there's nothing to download from the InputStream is. But if I use my browser to do the same thing, I'll get a response, composed of text lines of the following format:
CITY_NAME|SOME_DIGITS
So, can anybody tell me, how can I make such a request in an appropriate manner?
UPD: without cookies I have the same behaviour (in the browser everything's fine, but not in Java).
Can you please try with:
BufferedReader rd = null;
try {
URL url = new URL("https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503");
URLConnection conn = url.openConnection();
String cookie = (new RandomString(32)).nextString();
conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rd != null) {
try {
rd.close();
} catch (IOException e) {
}
}
}
This is peace of code that works properly in my projects. :)
Try the following thing.
HttpURLConnection connection = null;
try {
String url = "https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503";
URL url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
connection.connect();
connection.getInputStream();
int buffer;
while((buffer = is.read()) != -1)
System.out.print(buffer);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(null != connection) { connection.disconnect(); }
}