java.net.URISyntaxException: Relative path

在我用Maven package以后,运行java -jar target\test-0.0.1-SNAPSHOT.jar时提示有错误:

java.net.URISyntaxException: Relative path in absolute URI: java://file:/C:/Users/user/workspace/test/target/test-0.0.1-SNAPSHOT.jar!/lib/fooJDBC-1.0.jar!/

Loaded JDBC driver: com.foo.Driver

这个fooJDBC-1.0.jar是我用mvn install:install-file 命令添加到本地repository的,这样mvn打包的时候就能把这个jar也能打进去.

这个错看起来好象和感叹号有关.

为什么会出现这样的错误?该怎么解决?谢谢.

3个回答

是不是在URL中有感叹号

不知道那两个感叹号是怎么有的

有没有人会呀,请大家看看

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
jmeter发送请求java.net.URISyntaxException:
java.net.URISyntaxException: Malformed IPv6 address at index 8: http://[test.xdaili.cn:10003]/ at java.net.URI$Parser.fail(Unknown Source) at java.net.URI$Parser.parseIPv6Reference(Unknown Source) at java.net.URI$Parser.parseServer(Unknown Source) at java.net.URI$Parser.parseAuthority(Unknown Source) at java.net.URI$Parser.parseHierarchical(Unknown Source) at java.net.URI$Parser.parse(Unknown Source) at java.net.URI. (Unknown Source) at java.net.URL.toURI(Unknown Source) at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:331) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135) at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:465) at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:410) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:241) at java.lang.Thread.run(Unknown S
CXF调用webservice时 地址包含非法字符
报错是这个 java.net.URISyntaxException: Illegal character in path at index 0: \ 错误在这一行 createClient(sd); JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance(); String sd = "http://eastcao2046.eicp.net:7001/qjyyAppService/services/pushClient?wsdl"; Client clientTemp = clientFactory.createClient(sd);
测试spark集群入门级wordcount出错,求大神们帮忙解决啊
* Created by jyq on 10/14/15. */ 就这么点源代码 import org.apache.spark.{SparkConf,SparkContext,SparkFiles} object WordCount { def main(args: Array[String]):Unit= { val conf =new SparkConf().setAppName("WordCount").setMaster("spark://master:7077") val sc = new SparkContext(conf) sc.addFile("file:///home/jyq/Desktop/1.txt") val textRDD=sc.textFile(SparkFiles.get("file:///home/jyq/Desktop/1.txt")) val result = textRDD.flatMap(line =>line.split("\\s+") ).map(word=> (word, 1)).reduceByKey(_ + _) result.saveAsTextFile("/home/jyq/Desktop/2.txt") println("hello world") } } 在IDEA编译运行下输出的日志: Exception in thread "main" java.lang.IllegalArgumentException: java.net.URISyntaxException: Expected scheme-specific part at index 5: file: at org.apache.hadoop.fs.Path.initialize(Path.java:206) at org.apache.hadoop.fs.Path.<init>(Path.java:172) at org.apache.hadoop.fs.Path.<init>(Path.java:94) at org.apache.hadoop.fs.Globber.glob(Globber.java:211) at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1644) at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:257) at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228) at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313) at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:207) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.Partitioner$.defaultPartitioner(Partitioner.scala:65) at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290) at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:147) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:108) at org.apache.spark.rdd.RDD.withScope(RDD.scala:306) at org.apache.spark.rdd.PairRDDFunctions.reduceByKey(PairRDDFunctions.scala:289) at WordCount$.main(WordCount.scala:16) at WordCount.main(WordCount.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 5: file: at java.net.URI$Parser.fail(URI.java:2848) at java.net.URI$Parser.failExpecting(URI.java:2854) at java.net.URI$Parser.parse(URI.java:3057) at java.net.URI.<init>(URI.java:746) at org.apache.hadoop.fs.Path.initialize(Path.java:203) ... 41 more 15/10/15 20:08:36 INFO SparkContext: Invoking stop() from shutdown hook 15/10/15 20:08:36 INFO SparkUI: Stopped Spark web UI at http://192.168.179.111:4040 15/10/15 20:08:36 INFO DAGScheduler: Stopping DAGScheduler 15/10/15 20:08:36 INFO SparkDeploySchedulerBackend: Shutting down all executors 15/10/15 20:08:36 INFO SparkDeploySchedulerBackend: Asking each executor to shut down 15/10/15 20:08:36 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped! 15/10/15 20:08:36 INFO MemoryStore: MemoryStore cleared 15/10/15 20:08:36 INFO BlockManager: BlockManager stopped 15/10/15 20:08:36 INFO BlockManagerMaster: BlockManagerMaster stopped 15/10/15 20:08:36 INFO SparkContext: Successfully stopped SparkContext 15/10/15 20:08:36 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped! 15/10/15 20:08:36 INFO ShutdownHookManager: Shutdown hook called 15/10/15 20:08:36 INFO ShutdownHookManager: Deleting directory /tmp/spark-d7ca48d5-4e31-4a07-9264-8d7f5e8e1032 15/10/15 20:08:36 INFO RemoteActorRefProvider$RemotingTerminator: Shutting down remote daemon. Process finished with exit code 1
URL抛出URISyntaxException异常,请问怎么解决?
URL抛出URISyntaxException异常,请问怎么解决? java.net.URISyntaxException: Malformed escape pair at index 113: http://www.zuoche.com/pda/showmap.jsp?f=1&s=5508107&d=5511127&xy=32786,2559633,35024,2560043&k=fd120733&m=1&tt=1.%u4F53%u80B2%u4E2D%u5FC3%u7AD9%u2192%u534E%u5E08&ref=tid%3D4463987%2Ce9eb5f7e%26d%3D%25BB%25AA%25CA%25A6%26sid%3D5506916%2C659678f0%26m%3D1 at java.net.URI$Parser.fail(Unknown Source) at java.net.URI$Parser.scanEscape(Unknown Source) at java.net.URI$Parser.scan(Unknown Source) at java.net.URI$Parser.checkChars(Unknown Source) at java.net.URI$Parser.parseHierarchical(Unknown Source) at java.net.URI$Parser.parse(Unknown Source) at java.net.URI.<init>(Unknown Source) at com.iwidsets.browser.utils.URLUtil.makeAbsoluteUrl(URLUtil.java:44)
运行mapredurce出现Method threw 'java.lang.IllegalStateException' exception. Cannot evaluate org.apache.hadoop.mapreduce.Job.toString()
执行下述代码后在,创建job后会有上述异常,但是可以执行到最后,但是job没有提交上去执行,在历史里也看不到有执行记录求帮助新手o(╥﹏╥)o。 package MapReducer; import com.sun.org.apache.bcel.internal.generic.RETURN; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.StringTokenizer; /** * @Describe MapReducer第一个读取文档并计数 * @Author zhanglei * @Date 2019/11/18 22:53 **/ public class WordCountApp extends Configured implements Tool { public int run(String[] strings) throws Exception { String input_path="hdfs://192.168.91.130:8020/data/wc.txt"; String output_path="hdfs://192.168.91.130:8020/data/outputwc"; Configuration configuration = getConf(); final FileSystem fileSystem = FileSystem.get(new URI(input_path),configuration); if(fileSystem.exists(new Path(output_path))){ fileSystem.delete(new Path(output_path),true); } Job job = Job.getInstance(configuration,"WordCountApp"); job.setJarByClass(WordCountApp.class); job.setMapperClass(WordCountMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setReducerClass(WordCountReducer.class); job.setInputFormatClass(TextInputFormat.class); Path inpath = new Path(input_path); FileInputFormat.addInputPath(job,inpath); job.setOutputFormatClass(TextOutputFormat.class); Path outpath = new Path(output_path); FileOutputFormat.setOutputPath(job,outpath); return job.waitForCompletion(true) ? 0:1; } //继承 public static class WordCountMapper extends Mapper<Object,Text,Text,IntWritable>{ private final static IntWritable one= new IntWritable(1); private Text word = new Text(); public void map(Object key,Text value,Context context) throws IOException, InterruptedException { Text t = value; StringTokenizer itr = new StringTokenizer(value.toString()); while(itr.hasMoreTokens()){ word.set(itr.nextToken()); context.write(word,one); } } } public static class WordCountReducer extends Reducer<Object,Text,Text,IntWritable>{ private final static IntWritable res= new IntWritable(1); public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException { int sum = 0; for(IntWritable val:values){ sum+=val.get(); } res.set(sum); context.write(key,res); } } public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run(new WordCountApp(), args); System.exit(exitCode); } }
MapReducer 写入到数据库 报错
## 【 DBUserWritable 类 】 package org.neworigin.com.Database; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.lib.db.DBWritable; public class DBUserWritable implements DBWritable,WritableComparable{ private String name=""; private String sex=""; private int age=0; private int num=0; private String department=""; private String tables=""; @Override public String toString() { return "DBUserWritable [name=" + name + ", sex=" + sex + ", age=" + age + ", department=" + department + "]"; } public DBUserWritable(DBUserWritable d){ this.name=d.getName(); this.sex=d.getSex(); this.age=d.getAge(); this.num=d.getNum(); this.department=d.getDepartment(); this.tables=d.getTables(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getTables() { return tables; } public void setTables(String tables) { this.tables = tables; } public DBUserWritable(String name, String sex, int age, int num, String department, String tables) { super(); this.name = name; this.sex = sex; this.age = age; this.num = num; this.department = department; this.tables = tables; } public DBUserWritable() { super(); // TODO Auto-generated constructor stub } public void write(DataOutput out) throws IOException { // TODO Auto-generated method stub out.writeUTF(name); out.writeUTF(sex); out.writeInt(age); out.writeInt(num); out.writeUTF(department); out.writeUTF(tables); } public void readFields(DataInput in) throws IOException { // TODO Auto-generated method stub name = in.readUTF(); sex=in.readUTF(); age=in.readInt(); num=in.readInt(); department=in.readUTF(); tables=in.readUTF(); } public int compareTo(Object o) { // TODO Auto-generated method stub return 0; } public void write(PreparedStatement statement) throws SQLException { // TODO Auto-generated method stub statement.setString(1, this.getName()); statement.setString(2, this.getSex()); statement.setInt(3, this.getAge()); statement.setString(4, this.getDepartment()); } public void readFields(ResultSet resultSet) throws SQLException { // TODO Auto-generated method stub this.name=resultSet.getString(1); this.sex=resultSet.getString(2); this.age=resultSet.getInt(3); this.department=resultSet.getString(4); } } ## 【mapper】 package org.neworigin.com.Database; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class UserDBMapper extends Mapper<LongWritable, Text, Text, DBUserWritable> { DBUserWritable DBuser= new DBUserWritable(); @Override protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, DBUserWritable>.Context context) throws IOException, InterruptedException { String[] values=value.toString().split(" "); if(values.length==4){ DBuser.setName(values[0]); DBuser.setSex(values[1]); DBuser.setAge(Integer.parseInt(values[2])); DBuser.setNum(Integer.parseInt(values[3])); DBuser.setTables("t1"); System.out.println("mapper---t1---------------"+DBuser); context.write(new Text(values[3]),DBuser); } if(values.length==2){ DBuser.setNum(Integer.parseInt(values[0])); DBuser.setDepartment(values[1]); DBuser.setTables("t2"); context.write(new Text(values[0]),DBuser); //System.out.println("mapper --t2"+"--"+values[0]+"----"+DBuser); } } } ## 【reducer 】 package org.neworigin.com.Database; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class UserDBReducer extends Reducer<Text, DBUserWritable,NullWritable,DBUserWritable> { // public DBUserWritable db= new DBUserWritable(); @Override protected void reduce(Text k2, Iterable<DBUserWritable> v2, Reducer<Text, DBUserWritable, NullWritable,DBUserWritable>.Context context) throws IOException, InterruptedException { String Name=""; List<DBUserWritable> list=new LinkedList<DBUserWritable>(); for(DBUserWritable val : v2){ list.add(new DBUserWritable(val));//new 一个对象 给list // System.out.println("[table]"+val.getTables()+"----key"+k2+"---"+val); if(val.getTables().equals("t2")){ Name=val.getDepartment(); } } //键是 num for(DBUserWritable join : list){ System.out.println("[table]"+join.getTables()+"----key"+k2+"---"+join); if(join.getTables().equals("t1")){ join.setDepartment(Name); System.out.println("db-----"+join); context.write(NullWritable.get(), join); } } } } ## 【app】 package org.neworigin.com.Database; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.db.DBConfiguration; import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class UserDBAPP { public static void main(String[] args) throws Exception, URISyntaxException { // TODO Auto-generated method stub String INPUT_PATH="file:///E:/BigData_eclipse_database/Database/data/table1"; String INPUT_PATH1="file:///E:/BigData_eclipse_database/Database/data/table2"; // String OUTPUT_PARH="file:///E:/BigData_eclipse_database/Database/data/output"; Configuration conf = new Configuration(); // FileSystem fs=FileSystem.get(new URI(OUTPUT_PARH),conf); // if(fs.exists(new Path(OUTPUT_PARH))){ // fs.delete(new Path(OUTPUT_PARH)); // } Job job = new Job(conf,"mydb"); //设置数据库配置 DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver", "jdbc:mysql://localhost/hadoop", "root", "123456"); FileInputFormat.addInputPaths(job,INPUT_PATH); FileInputFormat.addInputPaths(job,INPUT_PATH1); job.setMapperClass(UserDBMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(DBUserWritable.class); job.setReducerClass(UserDBReducer.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(DBUserWritable.class); // FileOutputFormat.setOutputPath(job, new Path(OUTPUT_PARH)); //设置输出路径 DBOutputFormat.setOutput(job,"user_tables", "name","sex","age","department"); job.setOutputFormatClass(DBOutputFormat.class); boolean re = job.waitForCompletion(true); System.out.println(re); } } 【报错】ps 表链接 ,写到本地没问题 写到数据库 就报错; 17/11/10 11:39:11 WARN output.FileOutputCommitter: Output Path is null in cleanupJob() 17/11/10 11:39:11 WARN mapred.LocalJobRunner: job_local1812680657_0001 java.lang.Exception: java.io.IOException at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462) at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:529) Caused by: java.io.IOException at org.apache.hadoop.mapreduce.lib.db.DBOutputFormat.getRecordWriter(DBOutputFormat.java:185) at org.apache.hadoop.mapred.ReduceTask$NewTrackingRecordWriter.<init>(ReduceTask.java:541) at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:614) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:389) at org.apache.hadoop.mapred.LocalJobRunner$Job$ReduceTaskRunnable.run(LocalJobRunner.java:319) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) 17/11/10 11:39:12 INFO mapreduce.Job: Job job_local1812680657_0001 running in uber mode : false 17/11/10 11:39:12 INFO mapreduce.Job: map 100% reduce 0% 17/11/10 11:39:12 INFO mapreduce.Job: Job job_local1812680657_0001 failed with state FAILED due to: NA 17/11/10 11:39:12 INFO mapreduce.Job: Counters: 35
keytool生成证书,上传到azure中,但仍旧,显示认证失败
``` public class TestClient { private static ComputeManagementClient computeManagementClient; private static ManagementClient client; private static URI uri; private static String subscriptionId; private static String keyStoreLocation; private static String keyStorePassword; private static KeyStoreType keyStoreType; public static Configuration createConfiguration() throws IOException,URISyntaxException{ uri = new URI("https://management.core.windows.net/"); subscriptionId="1dd1940e-9979-476c-a5dc-79a7d31686fd"; keyStoreLocation="C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\AzureKeyStore.jks"; keyStorePassword="123456"; keyStoreType= KeyStoreType.fromString("jks"); Configuration configuration = ManagementConfiguration.configure(uri, subscriptionId, keyStoreLocation, keyStorePassword,keyStoreType); configuration.setProperty("testprefix.com.microsoft.windowsazure.services.core.Configuration.connectTimeout","3"); configuration.setProperty("testprefix.com.microsoft.windowsazure.services.core.Configuration.readTimeout","7"); return configuration; } /** * https://management.core.windows.net/1dd1940e-9979-476c-a5dc-79a7d31686fd/services/resourceextensions * @param args * @throws Exception */ public static void main(String[] args) throws Exception { computeManagementClient = ComputeManagementService.create(createConfiguration()); client = ManagementService.create(createConfiguration()); // get the list of regions LocationsListResponse response = client.getLocationsOperations().list(); ArrayList<LocationsListResponse.Location> locations = response.getLocations(); // write them out for( int i=0; i<locations.size(); i++){ System.out.println(locations.get(i).getDisplayName()); } HostedServiceListResponse hostedServiceListResponse = computeManagementClient.getHostedServicesOperations().list(); System.out.println("statusCode:"+hostedServiceListResponse.getStatusCode()); VirtualMachineExtensionListResponse virtualMachineExtensionListResponse = computeManagementClient.getVirtualMachineExtensionsOperations().list(); System.out.println("................response........................"); System.out.println("requestId:" + virtualMachineExtensionListResponse.getRequestId()); System.out.println("statusCode:"+virtualMachineExtensionListResponse.getStatusCode()); ArrayList<VirtualMachineExtensionListResponse.ResourceExtension> list= virtualMachineExtensionListResponse.getResourceExtensions(); if( list != null && !list.isEmpty() ){ for( VirtualMachineExtensionListResponse.ResourceExtension resourceExtension : list){ System.out.println("resourceExtension:"+resourceExtension.getName()); } } } } ``` 但依然报http 403错误 This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Code>ForbiddenError</Code> <Message> The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription. </Message> </Error>
java动态编译加载类问题
今天看到这个http://www.infoq.com/cn/articles/cf-java-byte-code 想试一试,但是编译通过之后的,想执行结果那,总是不成功。现在将代码贴上,望大神指点! [code="java"] package com.deep.byteOpera; import java.io.IOException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class CompilerTest { static class StringSourceJavaObject extends SimpleJavaFileObject { private String content = null; public StringSourceJavaObject(String name, String content) throws URISyntaxException { super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE); this.content = content; } public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return content; } } public static void main(String[] args) throws Exception { String className = "MainTest"; String methodName = "main"; String source = "public class "+className+" { public static String "+methodName+" () { System.out.println(\"Hello World!\"); return \"haha\";} }"; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); //动态编译 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); StringSourceJavaObject sourceObject = new CompilerTest.StringSourceJavaObject(className, source); Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(sourceObject); CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileObjects); boolean result = task.call(); System.out.println(result); if (result) { //编译成功,进行加载执行 // ClassLoader loader = fileManager.getClass().getClassLoader(); // ClassLoader loader = fileObjects.getClass().getClassLoader(); // ClassLoader loader = task.getClass().getClassLoader(); // ClassLoader loader = compiler.getClass().getClassLoader(); ClassLoader loader = CompilerTest.class.getClassLoader(); // ClassLoader loader = ToolProvider.getSystemToolClassLoader(); try { Class<?> clazz = loader.loadClass(className); Method method = clazz.getMethod(methodName, new Class<?>[] {}); Object value = method.invoke(null, new Object[] {}); System.out.println(value); } catch (Exception e) { e.printStackTrace(); } } } } [/code]
JAVA如何做一个简单的网址导航
只是几固定的网址而已了,刚开始学JAVA想让自己桌面上有个自己写的东东了。呵呵。自己硬着头皮写了一个,请您看看看得清晰不? 如何才能让他更简便了。谢谢 [code="java"]package wangzhi; import java.awt.*; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main{ public static void main(String []args){ JFrame jf=new JFrame("苏戈斯网址"); JPanel jp=new JPanel(new GridLayout(3,3)); JButton jb1=new JButton("百度一下"); jb1.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb2=new JButton("京东商城"); jb2.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb3=new JButton("卓越商城"); jb3.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb4=new JButton("Ajava"); jb4.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb5=new JButton("Google"); jb5.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb6=new JButton("JavaEye"); jb6.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb7=new JButton("名鞋库"); jb7.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb8=new JButton("五一社区"); jb8.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); JButton jb9=new JButton("果果博客"); jb9.addActionListener(new ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent e){ try { System.out.println("dda"); bactionPerformed(e); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); Toolkit kit=Toolkit.getDefaultToolkit(); Image image=kit.createImage("D:\\source\\image\\cat.png"); jf.setIconImage(image); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jp.add(jb1); jp.add(jb2); jp.add(jb3); jp.add(jb4); jp.add(jb5); jp.add(jb6); jp.add(jb7); jp.add(jb8); jp.add(jb9); jf.add(jp); jf.setSize(300,300); jf.setVisible(true); } public static void bactionPerformed(ActionEvent e) throws URISyntaxException{ java.net.URI uri = null; try { String a=e.getActionCommand(); String url=null; if(a.equals("百度一下")) url="http://baidu.com"; else if(a.equals("京东商城")) url="http://360buy.com"; else if(a.equals("卓越商城")) url="http://amazon.com.cn"; else if(a.equals("五一社区")) url="http://51.com"; else if(a.equals("Ajava")) url="http://ajava.org"; else if(a.equals("Google")) url="http://google.com"; else if(a.equals("名鞋库")) url="http://s.cn"; else if(a.equals("果果博客")) url="http://hi.baidu.com/guoguo6688/blog/"; else if(a.equals("JavaEye")) url="http://iteye.com"; uri = new java.net.URI(url); java.awt.Desktop.getDesktop().browse(uri); System.exit(0);//浏览网址并退出程序 } catch (IOException e1) { e1.printStackTrace(); } } } [/code] [img]http://dl.iteye.com/upload/attachment/452649/97a1e3bb-e240-3453-bb2f-47abacb8eafb.jpg[/img]
关于XACML创建Rule Condition的Function factory异常。
public static Apply createRuleCondition() throws URISyntaxException { List conditionArgs = new ArrayList(); // get the function that the condition uses FunctionFactory factory = FunctionFactory.getConditionInstance(); Function conditionFunction = null; try { # conditionFunction = # factory.createFunction("urn:oasis:names:tc:xacml:2.0:function:" # + "time-in-range");** } catch (Exception e) { // see comment in createTargetMatch() return null; } // now create the apply section that gets the designator value List applyArgs = new ArrayList(); factory = FunctionFactory.getGeneralInstance(); Function applyFunction = null; try { applyFunction = factory.createFunction("urn:oasis:names:tc:xacml:1.0:function:" + "time-one-and-only"); } catch (Exception e) { // see comment in createTargetMatch() return null; } URI designatorType = new URI("http://www.w3.org/2001/XMLSchema#time"); URI designatorId = new URI("urn:oasis:names:tc:xacml:1.0:environment:current-time"); AttributeDesignator designator = new AttributeDesignator( AttributeDesignator.ENVIRONMENT_TARGET, designatorType, designatorId, false, null); applyArgs.add(designator); Apply apply = new Apply(applyFunction, applyArgs, false); // add the new apply element to the list of inputs to the condition conditionArgs.add(apply); // create an AttributeValue and add it to the input list StringAttribute value = new StringAttribute("developers"); conditionArgs.add(value); // finally, create & return our Condition return new Apply(conditionFunction, conditionArgs, true); } 在运行至加黑部分时,出现异常,返回空值。 该如何解决呢? 谢谢了!
关于java代码创建hdfs文件夹权限问题
我创建的目录授予的权限为775,为什么实际上查看权限只是755,谁能详细介绍下hdfs的权限设计 ``` Configuration conf =null; FileSystem fs = null; @Before public void init() throws URISyntaxException, IOException, InterruptedException { conf = new Configuration(); fs= FileSystem.get(new URI("hdfs://192.168.210.37:9000/"),conf,"hadoop"); } @Test public void mkdir() throws Exception { fs.mkdirs(new Path("/hbase"),new FsPermission("775")); fs.close(); } ``` ![图片说明](https://img-ask.csdn.net/upload/201709/19/1505799830_992414.png)
Unresolved compilation problem:
发送短信的API所有的代码都如下了,但是报错 Exception in thread "main" java.lang.Error: Unresolved compilation problem: ``` package com.saikul.platform.common; /** * Created by bingone on 15/12/16. */ import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 短信http接口的java代码调用示例 * 基于Apache HttpClient 4.3 * * @author songchao * @since 2015-04-03 */ public class JavaSmsApi { //查账户信息的http地址 private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json"; //智能匹配模版发送接口的http地址 private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json"; //模板发送接口的http地址 private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json"; //发送语音验证码接口的http地址 private static String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json"; //编码格式。发送编码格式统一用UTF-8 private static String ENCODING = "UTF-8"; public static void main(String[] args) { JavaSmsApi.sendSmsByCloudFilm("13296715110", "111111"); } public static void sendSmsByCloudFilm(String mobile, String smsCode) { // 修改为您的apikey.apikey可在官网(http://www.yuanpian.com)登录后获取 String apikey = "de8cf78e834c1a441c4c69374e8a2598"; // 设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板) String text = "【轻庐踏雪】您的验证码是" + smsCode; try { // 修改为您要发送的手机号 JavaSmsApi.sendSms(apikey, text, mobile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 取账户信息 * * @return json格式字符串 * @throws java.io.IOException */ public static String getUserInfo(String apikey) throws IOException, URISyntaxException { Map<String, String> params = new HashMap<String, String>(); params.put("apikey", apikey); return post(URI_GET_USER_INFO, params); } /** * 智能匹配模版接口发短信 * * @param apikey apikey * @param text  短信内容 * @param mobile  接受的手机号 * @return json格式字符串 * @throws IOException */ public static String sendSms(String apikey, String text, String mobile) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("apikey", apikey); params.put("text", text); params.put("mobile", mobile); return post(URI_SEND_SMS, params); } /** * 通过模板发送短信(不推荐) * * @param apikey apikey * @param tpl_id  模板id * @param tpl_value  模板变量值 * @param mobile  接受的手机号 * @return json格式字符串 * @throws IOException */ public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("apikey", apikey); params.put("tpl_id", String.valueOf(tpl_id)); params.put("tpl_value", tpl_value); params.put("mobile", mobile); return post(URI_TPL_SEND_SMS, params); } /** * 通过接口发送语音验证码 * @param apikey apikey * @param mobile 接收的手机号 * @param code 验证码 * @return */ public static String sendVoice(String apikey, String mobile, String code) { Map<String, String> params = new HashMap<String, String>(); params.put("apikey", apikey); params.put("mobile", mobile); params.put("code", code); return post(URI_SEND_VOICE, params); } /** * 基于HttpClient 4.3的通用POST方法 * * @param url 提交的URL * @param paramsMap 提交<参数,值>Map * @return 提交响应 */ public static String post(String url, Map<String, String> paramsMap) { CloseableHttpClient client = HttpClients.createDefault(); String responseText = ""; CloseableHttpResponse response = null; try { HttpPost method = new HttpPost(url); if (paramsMap != null) { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> param : paramsMap.entrySet()) { NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue()); paramList.add(pair); } method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING)); } response = client.execute(method); HttpEntity entity = response.getEntity(); if (entity != null) { responseText = EntityUtils.toString(entity); } } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (Exception e) { e.printStackTrace(); } } return responseText; } } ``` BUG问题: Exception in thread "main" java.lang.Error: Unresolved compilation problem: at com.saikul.platform.common.JavaSmsApi.main(JavaSmsApi.java:48)
发送请求报 401 权限错误
前端报错信息 : ![图片说明](https://img-ask.csdn.net/upload/201803/28/1522207360_242358.png) 前端代码: ``` create(user: User): Observable<User> { return this.http.post(this.resourceUrl, user); } ``` 后台报错信息: ![图片说明](https://img-ask.csdn.net/upload/201803/28/1522207423_237959.png) 后台代码; ``` /** * POST /users : Creates a new user. * <p> * Creates a new user if the login and email are not already used, and sends an * mail with an activation link. * The user needs to be activated on creation. * * @param userDTO the user to create * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use */ @PostMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { log.debug("REST request to save User : {}", userDTO); if (userDTO.getId() != null) { throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); // Lowercase the user login before comparing with database } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { throw new LoginAlreadyUsedException(); } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { throw new EmailAlreadyUsedException(); } else { User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) .headers(HeaderUtil.createAlert( "userManagement.created", newUser.getLogin())) .body(newUser); } } ```
向后台发送请求, 数据增加成功,后台向前端返回值为显示失败, 不知道是什么原因
这是我的后台代码: ``` @PostMapping("/certifications") @Timed public ResponseEntity<Certification> createCertification(@RequestBody Certification certification) throws URISyntaxException { log.debug("REST request to save Certification : {}", certification); if (certification.getId() != null) { throw new BadRequestAlertException("A new certification cannot already have an ID", ENTITY_NAME, "idexists"); } log.info("certification的id {}", certification.getId()); Certification result = certificationRepository.save(certification); log.info("save 后的certifications {}", result.getId()); System.out.println("/api/certifications/" + result.getId()); System.out.println(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())); return ResponseEntity.created(new URI("/api/certifications/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } ``` 这是我前端代码: ``` this.certification.type = '身份证'; this.certification.isverify = '未审核'; this.certification.userId = this.user.id; console.log("进入examine()"); console.log(this.certification); this.isSaving = true; if (this.certification.id !== undefined) { this.subscribeToSaveResponse( this.certificationProvider.update(this.certification)); } else { this.subscribeToSaveResponse( this.certificationProvider.create(this.certification)); } console.log("实名认证完成"); create(certification: Certification): Observable<Certification> { const copy = this.convert(certification); return this.http.post(this.resourceUrl, copy).map((res: Response) => { console.log("Response 的"+res.json()); const jsonResponse = res.json(); console.log("jsonResponse 的"+jsonResponse); return this.convertItemFromServer(jsonResponse); }); } private subscribeToSaveResponse(result: Observable<Certification>) { //noinspection TypeScriptUnresolvedVariable console.log("subscribeToSaveResponse 里的 result"+result); result.subscribe((res: Certification) => this.onSaveSuccess(res), (res: Response) => this.onSaveError()); } private onSaveSuccess(result: Certification) { this.event.publish('carListModification', 'OK'); this.isSaving = false; this.view.dismiss(result); } private onSaveError() { this.isSaving = false; console.log("失败"); } ```
httpie 形式 用 httpclient 改写问题
http PATCH 127.0.0.1:8080/db/col/*?filter={'__i d':{'$oid':'577b07800385b141c4d13ad1'},'submenu.subcode':'B013'} "submenu.$.subname"="test123" 现在要将上面的httpie 语句用httpclient 改写,我写的代码如下: public static String getContentByPara(String url){ String result= ""; DefaultHttpClient client = new DefaultHttpClient(); HttpPut httppatch = new HttpPut("127.0.0.1:8080/db/col/*"); httppatch.setHeader("Content-Type", "application/hal+json"); JSONObject para = new JSONObject(); para.put("submenu.$.subname", "test123"); try { List<NameValuePair> temp = new ArrayList<NameValuePair>(); temp.add(new BasicNameValuePair("filter", "{'_id':{'$oid':'577b07800385b141c4d13ad1'},'submenu.subcode':'B013'}")); String str = EntityUtils.toString(new UrlEncodedFormEntity(temp,"UTF-8")); httppatch.setEntity(new StringEntity(para.toString(),"UTF-8")); httppatch.setURI(new URI(httppatch.getURI().toString() + "?"+ str)); HttpResponse httpResponse = client.execute(httppatch); System.out.println(httpResponse.getStatusLine().toString()); if(httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); // System.out.println(result); }else{ httppatch.abort(); } } catch (ClientProtocolException e1){ e1.printStackTrace(); }catch (IOException e2){ e2.printStackTrace(); }catch (URISyntaxException e) { e.printStackTrace(); }finally { httppatch.releaseConnection(); } return null; } 但是报HTTP/1.1 405 Method Not Allowed
项目加入消息推送功能,我打算用socket io实现,但遇到了问题
private Socket mSocket; { try { mSocket = IO.socket(Constants.CHAT_SERVER_URL); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public Socket getSocket() { return mSocket; } import io.socket.client.IO; import io.socket.client.Socket; 例子中导了这两个包,但就是找不到这两个包,上网上也没搜到。 有没有人知道该怎么做啊。
亚马逊 mws对接系统时SignatureDoesNotMatch报错
错误内容: <?xml version="1.0"?> <ErrorResponse xmlns="https://mws.amazonservices.com/Orders/2013-09-01"> <Error> <Type>Sender</Type> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> </Error> <RequestID>23142876-a0db-42f5-9ba9-527313c7bb78</RequestID> </ErrorResponse> 我的代码: public class TestUtl { private static final String CHARACTER_ENCODING = "UTF-8"; final static String ALGORITHM = "HmacSHA256"; public static void main(String[] args) throws Exception { String timestamp = AmazonTimeUtil.getAmaZonTime(); String secretKey = "iXvQ+bHDVSkaMBaXXXXXXXXXXXXXXXX"; // Use the endpoint for your marketplace String serviceUrl = "https://mws.amazonservices.com/"; // Create set of parameters needed and store in a map HashMap<String, String> parameters = new HashMap<String, String>(); // Add required parameters. Change these as needed. parameters.put("AWSAccessKeyId", urlEncode("AKIAJXAAD6Y2XXXXXXXX")); parameters.put("SignatureMethod", urlEncode("HmacSHA256")); parameters.put("SignatureVersion", urlEncode("2")); // parameters.put("SubmittedFromDate",urlEncode(submittedFromDate)); // parameters.put("SubmittedFromDate",getFormattedTimestamp()); parameters.put("Timestamp", urlEncode(timestamp)); parameters.put("Version", urlEncode("2013-09-01")); parameters.put("Action", urlEncode("ListOrders")); parameters.put("MarketplaceId",urlEncode("ATVPDKIKX0DER")); parameters.put("CreatedAfter", urlEncode("2016-05-25T10:56:00Z")); parameters.put("SellerId", urlEncode("A1VGN18HFINRY8")); parameters.put("MWSAuthToken", urlEncode("amzn.mws.b2a759cd-f24d-80f6-3cce-b543342ddd7a")); String formattedParameters = calculateStringToSignV2(parameters, serviceUrl); String signature = sign(formattedParameters, secretKey); Map<String, String> sorted = new TreeMap<String, String>(); sorted.putAll(parameters); // Add signature to the parameters and display final results parameters.put("Signature", urlEncode(signature)); System.out.println(calculateStringToSignV2(parameters, serviceUrl)); String pa = HttpUtils.prepareParam(sorted); System.out.println("url的值为:"+"https://mws.amazonservices.com/Orders/2013-09-01/?"+pa+"&Signature="+urlEncode(signature)+"\n"); try { URL url = new URL("https://mws.amazonservices.com/Orders/2013-09-01/?"+pa+"&Signature="+urlEncode(signature)); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setConnectTimeout(50000); BufferedReader br = null; StringBuffer sbOrderResponse = new StringBuffer(); String order = ""; String str = ""; InputStream inputstream = null; if (conn.getResponseCode() != 200) { inputstream = conn.getErrorStream(); } else { inputstream = conn.getInputStream(); } br = new BufferedReader(new InputStreamReader((inputstream))); StringBuffer buffer = new StringBuffer(); while ((order = br.readLine()) != null) { sbOrderResponse.append(order); str = str + order + "\n"; } System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage()); System.out.println(str); } catch (Exception e) { System.out.println("Error " + e); } } private static String calculateStringToSignV2(Map<String, String> parameters, String serviceUrl) throws SignatureException, URISyntaxException { // Sort the parameters alphabetically by storing // in TreeMap structure Map<String, String> sorted = new TreeMap<String, String>(); sorted.putAll(parameters); // Set endpoint value URI endpoint = new URI(serviceUrl.toLowerCase()); // Create flattened (String) representation StringBuilder data = new StringBuilder(); data.append("GET\n"); data.append(endpoint.getHost()); data.append("\n/Orders/2013-09-01"); // /Orders/2013-09-01 data.append("\n"); Iterator<Entry<String, String>> pairs = sorted.entrySet().iterator(); while (pairs.hasNext()) { Map.Entry<String, String> pair = pairs.next(); if (pair.getValue() != null) { data.append(pair.getKey() + "=" + pair.getValue()); } else { data.append(pair.getKey() + "="); } // Delimit parameters with ampersand (&) if (pairs.hasNext()) { data.append("&"); } } return data.toString(); } /* * Sign the text with the given secret key and convert to base64 */ private static String sign(String data, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { Mac mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(secretKey.getBytes(CHARACTER_ENCODING), ALGORITHM)); byte[] signature = mac.doFinal(data.getBytes(CHARACTER_ENCODING)); String signatureBase64 = new String(Base64.encodeBase64(signature), CHARACTER_ENCODING); return new String(signatureBase64); } private static String urlEncode(String rawValue) { String value = (rawValue == null) ? "" : rawValue; String encoded = null; try { encoded = URLEncoder.encode(value, CHARACTER_ENCODING).replace("+", "%20").replace("*", "%2A") .replace("%7E", "~"); } catch (UnsupportedEncodingException e) { System.err.println("Unknown encoding: " + CHARACTER_ENCODING); e.printStackTrace(); } return encoded; } }
android开发中url的openConnection()不能被IDE识别怎么办?
new AsyncTask<String, Float, String>() { @Override protected String doInBackground(String... params) { try { URI url = new URI(params[0]); URLConnection connection=url.openConnection();//这行的openConnection显示为红色 long total = connection.getContentLength(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line=br.readLine())!=null){ sb.append(line); publishProgress((float)sb.toString().length()/total); } br.close(); is.close(); return sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null;
相见恨晚的超实用网站
搞学习 知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www.51zxw
花了20分钟,给女朋友们写了一个web版群聊程序
参考博客 [1]https://www.byteslounge.com/tutorials/java-ee-html5-websocket-example
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
引言 本文主要是记录一下面试字节跳动的经历。 三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成喔~) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch
深深的码丨Java HashMap 透析
HashMap 相关概念 HashTab、HashMap、TreeMap 均以键值对像是存储或操作数据元素。HashTab继承自Dictionary,HashMap、TreeMap继承自AbstractMap,三者均实现Map接口 **HashTab:**同步哈希表,不支持null键或值,因为同步导致性能影响,很少被使用 **HashMap:**应用较多的非同步哈希表,支持null键或值,是键值对...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
JDK12 Collectors.teeing 你真的需要了解一下
前言 在 Java 12 里面有个非常好用但在官方 JEP 没有公布的功能,因为它只是 Collector 中的一个小改动,它的作用是 merge 两个 collector 的结果,这句话显得很抽象,老规矩,我们先来看个图(这真是一个不和谐的图????): 管道改造经常会用这个小东西,通常我们叫它「三通」,它的主要作用就是将 downstream1 和 downstre...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
相关热词 c# 输入ip c# 乱码 报表 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件
立即提问